3

I know that every literal in C and C++ get a specific type information. I have written this little program in C and compiled this in Visual Studio 2012. The source file is called 'main.c'.

#include <stdio.h>
int main()
{
    printf("sizeof(char) = %d\n",sizeof(char));
    printf("sizeof('i') = %d",sizeof('i'));
    getchar();
    return 0;
}

Output:

sizeof(char) = 1
sizeof('i') = 4

I wondered that the size of a character wasn't 1 Byte. I renamed the source file to 'main.cpp' and now sizeof('a') returned 1 as previously expected. So there must be a language specific difference. Why is the size of a char in C 4 Byte and not 1 ?

T.C.
  • 133,968
  • 17
  • 288
  • 421
Skydef
  • 61
  • 7

2 Answers2

10

Because in C++ the type of character literals is char, while in C it is int. Of course sizeof(char) itself is 1 in both languages by definition.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • *Why is the size of a character literal in C different than in C++?* Your answer is *in C++ the type of character literals is char, while in C it is int*. I guess the underlying OP question is: why is a character literal `int` in C and not `char` as in C++. – ouah Jan 05 '15 at 16:49
  • @ouah: I can't agree with that. The question says "why is the size of a char....", which clearly highlights a misconception: that a character literal is of type `char`. One would need to clear that up before being in the position to ask why it happens. – Jon Jan 05 '15 at 16:54
5

In C, 'i' has type int for backwards-compatibility reasons. Thus sizeof('i') shows the size of an int on the chosen compilation platform.

In C++, because overloading made it more urgent to avoid giving surprising types to expression, it was decided to break backwards compatibility and to give 'i' the type char.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281