The difference between 0 and '0' in array

拜拜、爱过 提交于 2020-01-20 07:17:44

问题


I have a question about array initialization

What is the difference between

char a[6]={0};

and

char a[6]={'0','0','0','0','0','0'};

How does the compiler interpret the above two expression? Are they just the same or not??


回答1:


'0' is the ASCII character for the number 0. Its value is 48.

The constant 0 is a zero byte or null byte, also written '\0'.

These four are equivalent:

char a[6] = {0};
char a[6] = {0, 0, 0, 0, 0, 0};
char a[6] = {'\0', '\0', '\0', '\0', '\0', '\0'};
char a[6] = "\0\0\0\0\0"; // sixth null byte added automatically by the compiler



回答2:


'0' is a character which is displayed (e.g. on a screen) so it looks like a zero. In all standard character sets, it has a non-zero numeric value. For example, in the ASCII character set it has numeric value 48.

0 is a literal which yields a numeric value of zero. '\0' is a literal which gives a character with numeric value of zero.

Putting values into an array does not change this.

You can test this using something like

#include <iostream>

int main()
{
    std::cout << "Character \'0\' does "
    if (0 != '0') std::cout << "not ";
    std::cout << "have numeric value zero\n";

    std::cout << "Character \'\\0\' does "
    if (0 != '\0') std::cout << "not ";
    std::cout << "have numeric value zero\n";
    return 0;
}

which will always print out

Character '0' does not have numeric value zero
Character '\0' does have numeric value zero

Some compilers may give a warning on the above code because 0 (unadorned) is of type int, '0' is of type char, and '\0' is also of type char. (There may also be warnings because the comparisons involve values known at compile time). The comparisons are allowed, but involve type conversions which can indicate programmer mistakes in some circumstances.



来源:https://stackoverflow.com/questions/32918600/the-difference-between-0-and-0-in-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!