Possible Duplicate:
Why are C character literals ints instead of chars?
#include<stdio.h>
int main(void)
{
char b = 'c';
printf("here size is %zu\n",sizeof('a'));
printf("here size is %zu",sizeof(b));
}
here output is (See live demo here.)
here size is 4
here size is 1
I am not getting why sizeof('a')
is 4 ?
Because in C character constants, such as 'a' have the type int
.
There's a C FAQ about this suject:
Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs).
The following is the famous line from the famous C
book - The C programming Language
by Kernighan & Ritchie
with respect to a character written between single quotes.
A character written between single quotes represents an integer value equal to the numerical value of the character in the machine's character set.
So sizeof('a')
is equivalent to sizeof(int)
'a' by default is an integer and because of that you get size of int in your machine 4 bytes.
char is 1 bytes and because of this you get 1 bytes.
来源:https://stackoverflow.com/questions/8654837/why-sizeofa-is-4-in-c