Why is the output for the following program 4?
#include <stdio.h>
int main()
{
printf("%d\n", sizeof('3'));
return 0;
}
Why is the output for the following program 4?
#include <stdio.h>
int main()
{
printf("%d\n", sizeof('3'));
return 0;
}
Because the type of a character constant is int, not char (and the size of int on your platform is four).
The C99 draft specification says:
An integer character constant has type int.
This might seem weird, but remember that you can do this:
const uint32_t png_IHDR = 'IHDR';
In other words, a single character constant can consist of more than one actual character (four, above). This means the resulting value cannot have type char, since then it would immediately overflow and be pointless.
Note: the above isn't a very nice way of doing what it seems to be implying, that's another discussion. :)
Character literal is int.
In C type of character constant Like '3' is int.
sizeof(character_constant)==sizeof(int)==> In your case sizeof(int)==4
Where As the in C++ it is char
This difference can lead to inconsistent behavior in some code that is compiled as both C and C++.
memset(&i, 'a', sizeof('a')); // Questionable code