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 ?
Since int in an integer type variable. So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.
Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.
The char type takes 1 byte of memory (8 bits) and allows expressing in the binary notation 2^8=256 values.
When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32-bit system can show different output while a 64-bit system can show different of same data types.
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)
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