Warning : overflow in implicit constant conversion

前端 未结 4 2030
醉话见心
醉话见心 2021-01-01 17:30

In the following program, the line 5 does give overflow warning as expected, but surprisingly the line 4 doesn\'t give any warning in GCC: http://www.ideone.com/U0

4条回答
  •  时光说笑
    2021-01-01 18:23

    In the general case of assigning an int value to a char object, the compiler doesn't know whether the int is out of range of the char.

    Look at the actual warning more closely:

    warning: overflow in implicit constant conversion
    

    It is in this specific case, where a constant is being converted to char that the compiler is able to warn you. Likewise, if you changed the declaration of i to be const:

    const int i = 256;
    

    you will also get the warning, because the value being assigned to c2 is a constant expression.

    Note also that the warning is somewhat misleading as the conversion does not technically "overflow." Arithmetic overflow yields undefined behavior in C++. A narrowing conversion (like int to char, if int has a larger range than char) yields some implementation-defined conversion.

提交回复
热议问题