Possible Duplicate:
Why are C character literals ints instead of chars?
http://ideone.com/lHYY8
int main(void)
{
printf("%d %d\n", sizeof('c'), sizeof(char));
return 0;
}
Why does sizeof('c')
return 4 instead of 1?
Because in C character constants have the type int
, not char
. So sizeof('c') == sizeof(int)
. Refer to this C FAQ
Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs).
One (possibly even more extreme) oddity that also somehow justifies this, is the fact that character literals are not limited to being single character.
Try this:
printf("%d\n", 'xy');
This is sometimes useful when dealing with e.g. binary file formats that use 32-bit "chunk" identifiers, such as PNG. You can do things like this:
const int chunk = read_chunk_from_file(...);
if(chunk == 'IHDR')
process_image_header(...);
There might be portability issues with code like this though, of course the above snippet assumes that read_chunk_from_file()
magically does the right thing to transform the big-endian 32-bit value found in the PNG file into something that matches the value of the corresponding multi-character character literal.
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