C语言 字符串终止 - char c=0 vs char c='\0'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16955936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String termination - char c=0 vs char c='\0'
提问by Joe DF
When terminating a string, it seems to me that logically char c=0is equivalent to char c='\0', since the "null" (ASCII 0) byte is 0, but usually people tend to do '\0'instead. Is this purely out of preference or should it be a better "practice"?
当终止一个字符串时,在我看来这在逻辑上char c=0等同于char c='\0',因为“空”(ASCII 0)字节是0,但通常人们倾向于这样做'\0'。这纯粹是出于偏好还是应该是更好的“实践”?
What is the preferred choice?
什么是首选?
EDIT:K&Rsays: "The character constant '\0'represents the character with value zero, the null character. '\0'is often written instead of 0to emphasize the character nature of some expression, but the numeric value is just 0.
编辑:K&R说:“字符常量'\0'表示值为 0 的字符,即空字符。'\0'经常被写入而不是0为了强调某些表达式的字符性质,但数值只是0.
采纳答案by Nobilis
http://en.wikipedia.org/wiki/Ascii#ASCII_control_code_chart
http://en.wikipedia.org/wiki/Ascii#ASCII_control_code_chart
Binary Oct Dec Hex Abbr Unicode Control char C Escape code Name
0000000 000 0 00 NUL ? ^@ ##代码## Null character
There's no difference, but the more idiomatic one is '\0'.
没有区别,但更惯用的是'\0'。
Putting it down as char c = 0;could mean that you intend to use it as a number (e.g. a counter). '\0'is unambiguous.
放下它char c = 0;可能意味着您打算将其用作数字(例如计数器)。'\0'是明确的。
回答by Michal Bukovy
'\0'is just an ASCII character. The same as 'A', or '0'or '\n'
If you write char c = '\0', it's the same aschar c = 0;
If you write char c = 'A', it's the same as char c = 65
'\0'只是一个 ASCII 字符。与'A', or '0'or相同'\n'
如果你写char c = '\0',它和你写的一样char c = 0;
如果你写char c = 'A',它和char c = 65
It's just a character representation and it's a good practice to write it, when you really mean the NULL byte of string. Since charis in C one byte (integral type), it doesn't have any special meaning.
它只是一种字符表示,当您真正指的是字符串的 NULL 字节时,编写它是一种很好的做法。由于char在 C 中是一个字节(整型),所以它没有任何特殊含义。
回答by Pupkov-Zadnij
Preferred choice is that which can give people reading your code an ability to understand how do you use your variable - as a number or as a character. Best practice is to use 0 when you mean you variable as a number and to use '\0' when you mean your variable is a character.
首选的选择是让阅读您代码的人能够理解您如何使用您的变量 - 作为数字或字符。最佳实践是当您将变量表示为数字时使用 0,当您将变量表示为字符时使用 '\0'。

