Warning : overflow in implicit constant conversion

前端 未结 4 2031
醉话见心
醉话见心 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:01

    Well, line 5 is an obvious error that any compiler can see directly, and always an error. Line 4 would require at least some data flow analysis to discover the error. Perhaps this isn't done with the settings used at the site, or perhaps the compiler writers didn't consider this important enough to figure it out.

    0 讨论(0)
  • 2021-01-01 18:15

    Post GCC 4.3, the semantics of -Wconversion have been updated to detect implicit conversions that might change a value, but you have to enable -Wsign-conversion as well, because otherwise you won't get a warning for code that might change the sign of a number due to coercion between signed and unsigned types.

    Contrary to what Crazy Eddie is saying, prior to GCC 4.3 (which hadn't been released yet at the time) -Wconversion didn't generically check for problems introduced by implicit type conversion and the like. Rather, it checked whether your program would behave differently than it would have behaved if it had used old-style K&R function prototypes.

    This not only meant that it didn't give a warning on all implicit type conversion / coercion problems, but it also meant that some good code gave an unnecessary warning. And of course, you'd get no error with g++ because such prototypes aren't valid C++ anyway.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-01 18:24

    -Wall doesn't include many options. -Wconversion is one of them and warns about the behavior you're interested in.

    See http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

    0 讨论(0)
提交回复
热议问题