Addition of two chars produces int

后端 未结 3 1064
遥遥无期
遥遥无期 2020-11-27 06:49

I\'ve made a simple program and compiled it with GCC 4.4/4.5 as follows:

int main ()
{
  char u = 10;
  char x = \'x\';
  char i = u + x;

  return 0;
}
         


        
3条回答
  •  生来不讨喜
    2020-11-27 07:23

    When you do any arithmetic operation on char type, the result it returns is of int type.

    See this:

    char c = 'A';
    cout << sizeof(c) << endl;
    cout << sizeof(+c) << endl;
    cout << sizeof(-c) << endl;
    cout << sizeof(c-c) << endl;
    cout << sizeof(c+c) << endl;
    

    Output:

    1
    4
    4
    4
    4

    Demonstration at ideone : http://www.ideone.com/jNTMm

提交回复
热议问题