Strange GCC short int conversion warning

后端 未结 6 607
南笙
南笙 2021-01-18 15:41

I have a bit of C code, which goes exactly like this:

short int fun16(void){
    short int a = 2;
    short int b = 2;
    return a+b;
}

Wh

6条回答
  •  不思量自难忘°
    2021-01-18 16:42

    When you do arithmetic computations, the operands are subject to "the usual arithmetic conversions" (a superset of the "integer promotions" quoted in Acme's answer—he beat me to this but I'll go ahead and post anyway :-) ). These widen short int to plain int, so:

    a + b
    

    computes the same result as:

    ((int) a) + ((int) b)
    

    The return statement must then narrow this int to a short int, and this is where gcc produces the warning.

提交回复
热议问题