Question

In C, why is sizeof(char) 1, when 'a' is an int?

I tried

printf("%d, %d\n", sizeof(char), sizeof('c'));

and got 1, 4 as output. If size of a character is one, why does 'c' give me 4? I guess it's because it's an integer. So when I do char ch = 'c'; is there an implicit conversion happening, under the hood, from that 4 byte value to a 1 byte value when it's assigned to the char variable?

 45  25206  45
1 Jan 1970

Solution

 36

In C 'a' is an integer constant (!?!), so 4 is correct for your architecture. It is implicitly converted to char for the assignment. sizeof(char) is always 1 by definition. The standard doesn't say what units 1 is, but it is often bytes.

2010-02-12

Solution

 7

Th C standard says that a character literal like 'a' is of type int, not type char. It therefore has (on your platform) sizeof == 4. See this question for a fuller discussion.

2010-02-12