Possible Duplicate:
Size of character ('a') in C/C++
The following program
#include <stdio.h>
int main()
{
printf("%d\n", sizeof('\0'));
printf("%d\n", sizeof(0));
}
compiled with gcc outputs
4
4
and with g++
1
4
Why is this happening? I know this it's not a compiler thing but a difference between C and C++ but what's the reason?
In C, character constants have type int
per 6.4.4.4(10) of the standard,
An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer.
Thus you're printing out the size of an int
twice.
In C++, character constants have type char
.
The \0
character literal is treated as an int
in C, so you actually end up printing sizeof(int)
instead of sizeof(char)
.
ideone
gives the same results (C, C++).
In C character literals are ints. In C++ they are chars.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With