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??
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??
'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
'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.