Consider the program
main()
{
printf("%d %d %d",sizeof('3'),sizeof("3"),sizeof(3));
}
output from a gcc compiler is:
4 2 4
Why is it so?
Consider the program
main()
{
printf("%d %d %d",sizeof('3'),sizeof("3"),sizeof(3));
}
output from a gcc compiler is:
4 2 4
Why is it so?
Assuming you are running on a 32-bit system:
sizeof a character literal '3' is 4 because character literals are ints in C language (but not C++).
sizeof "3" is 2 because it is an array literal with length 2 (numeral 3 plus NULL terminator).
sizeof literal 3 is 4 because it is an int.
A few points to keep in mind:
sizeof
isn't a function, it's an operator. It returns the size of a type in units of sizeof char
. In other words sizeof char
is always 1.int
char[2]
, the character 3 then the null terminator.int
With these the differences are easily explained:
int
requires 4 char
s of space to hold itchar[2]
naturally only requires 2 char
sTo quote K & R,
Each compiler is free to choose appropriate sizes for its own hardware, subject only to the the restriction that shorts and ints are at least 16 bits, longs are at least 32 bits, and short is no longer than int, which is no longer than long.