Why is the size of a character character in C different from C ++

I know that every literal in C and C ++ gets information of a certain type. I wrote this little C program and compiled it 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 if the character size was not 1 byte. I renamed the original file to 'main.cpp' and now sizeof ('a') has returned 1 as expected earlier. So there must be a difference in language. Why is the size of char in C 4 bytes and not 1?

+3


source to share


2 answers


In C, 'i'

has a type int

for backward compatibility reasons. Thus, it sizeof('i')

shows the size int

on the chosen compilation platform.



In C ++, because overloading made it more urgent to avoid expressing awesome types for an expression, it was decided to drop backward compatibility and give a 'i'

type char

.

+5


source


Because in C ++ the type is character literals char

, and in C it is int

. Of course, sizeof(char)

by itself is 1 in both languages.



+10


source







All Articles