Why are C character literals ints instead of chars?

后端 未结 12 859
悲哀的现实
悲哀的现实 2020-11-22 02:24

In C++, sizeof(\'a\') == sizeof(char) == 1. This makes intuitive sense, since \'a\' is a character literal, and sizeof(char) == 1 as d

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:02

    using gcc on my MacBook, I try:

    #include 
    #define test(A) do{printf(#A":\t%i\n",sizeof(A));}while(0)
    int main(void){
      test('a');
      test("a");
      test("");
      test(char);
      test(short);
      test(int);
      test(long);
      test((char)0x0);
      test((short)0x0);
      test((int)0x0);
      test((long)0x0);
      return 0;
    };
    

    which when run gives:

    'a':    4
    "a":    2
    "":     1
    char:   1
    short:  2
    int:    4
    long:   4
    (char)0x0:      1
    (short)0x0:     2
    (int)0x0:       4
    (long)0x0:      4
    

    which suggests that a character is 8 bits, like you suspect, but a character literal is an int.

提交回复
热议问题