#include <stdio.h>
int main()
{
char c = '0';
printf("%d %d",sizeof(c), sizeof('0'));
return 0;
}
I expect the output is 1 1.but the real result is 1 4.
#include <stdio.h>
int main()
{
char c = '0';
printf("%d %d",sizeof(c), sizeof('0'));
return 0;
}
I expect the output is 1 1.but the real result is 1 4.
Opposite to C++ in C (integer) character constants have the type int
.
From the C Standard (6.4.4.4 Character constants)
10 An integer character constant has type int.
Compare the quote with the quote from the C++17 Standard (5.13.3 Character literals)
2 A character literal that does not begin with u8, u, U, or L is an ordinary character literal. An ordinary character literal that contains a single c-char representable in the execution character set has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set....
As for this expression
sizeof(c)
then it provides the size of an object of the type char
. Objects of the type char
always have the size equal to 1
.
From the C Standard (6.5.3.4 The sizeof and alignof operators)
4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1....
Pay attention to that a valid call of the function printf will look like
printf("%zu %zu",sizeof(c), sizeof('0'));
Character literals ('0'
, 'a'
, 'd'
, '.'
) in C are of type int
(unlike in C++, where they are of type char
).
So you will get in C:
sizeof(char) == 1
sizeof('0') == sizeof(int) // note that this is not necessarily 4!
whereas in C++ you will have:
sizeof(char) == 1
sizeof('0') == sizeof(char)
sizeof('0')
is actually
sizeof(ASCII value of '0')
which is integer. Thus it is printing sizeof(int)
.