char ch = 'a';
Here ch is a character variable, so it's size is one byte. 'a' is a character constant,so it's ASCII value will be stored which is 2 byte.But how could it possible to store a 2 byte value in an 1 byte variable ?
char ch = 'a';
Here ch is a character variable, so it's size is one byte. 'a' is a character constant,so it's ASCII value will be stored which is 2 byte.But how could it possible to store a 2 byte value in an 1 byte variable ?
A character literal, such as 'a'
, will be treated as an integer literal, such as 97
or 0x61
. C compilers tend to want every integer to be stored in an int
unless told otherwise, so sizeof('a')
will probably be sizeof(int)
.
You should notice, though, that the value of 'a'
is less than 127 so it can be stored in a char (which has a maximum value of either 127 or 255 depending on if it is signed or unsigned on your compiler). This is the same as being able to:
unsigned long long x = 0;
unsigned int y = x;
y
is assigned from a x
whose type is bigger than y
's type, but x
's value is well within those which y
can represent, so no data is lost when the top bits (all 0s) are chopped off.
Along with other people's responces more somewhat related information can be found at this question.
You've asked a good question. I suggest that you do two things to satisfy yourself that there is enough room to store a character:
1) Look at the documentation for getchar(), and you will see it returns an int, so there is enough room to store a character's value. It is good to understand the underpinnings of the declaration, but if you declare char cTestChar = 'c';
there is enough room to store the value.
2) Generate an assembly listing when you compile. Visual C/C++ supports this as well as gcc. gcc uses the -Wa option to generate assembly output. The map will show the allocation of a character type.