tags:

views:

90

answers:

3
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: 

Well a character constant is only one byte...

tibur
The type of a character literal is actually `int` in C.
detly
`sizeof('c')` returns 1 with VS2010 and gcc 4.3
tibur
We're talking about C, not C++. In C++, `sizeof('c')` is 1.
AndiDog
+3  A: 

Along with other people's responces more somewhat related information can be found at this question.

Shynthriir
+2  A: 

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.

nategoose