Test ENV
- Linux
- Intel x86-64 GCC 8.2.1
- Flags enabled:
-Wextra -Wall -Wfloat-equal -Wundef -Wshadow -Winit-self -Wpointer-arith -Wcast-align -Wstrict-prototypes -Wstrict-overflow=5 -Wwrite-strings -Waggregate-return -Wcast-qual -Wswitch-default -Wswitch-enum -Wconversion -Wunreachable-code -Wformat=2 -pedantic -pedantic-errors -Werror-implicit-function-declaration -Wformat-security -fstrict-overflow
sizeof(long)
is 8.sizeof(int)
is 4.
Example 1, got a warning, good:
long x = 2147483647 * 3;
Example 2, no warning, not good:
long x = 2147483647U * 3U; // Suffix U
or
unsigned int a = 2147483647;
unsigned int b = 3;
long x = a*b;
Example 3, no warning, but work as expected:
long x = 2147483647L * 3L; // Suffix L
In the example 2, I know that it is a wrap-around instead of integer overflow, but these are those cases that the compiler are unable to warn about?
From the Standard:
(6.3.1.8)
Otherwise, the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:
If both operands have the same type, then no further conversion is needed. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
(6.5):
If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its (type), the behavior is undefined.
Started using Clang with flag -fsanitize=unsigned-integer-overflow
that helps a lot with undesired values from wrap-around. That is not an integer overflow, but not the intended value. Since GCC, until now does not support a warning like this, moving on to Clang.
unsigned
integers never overflow; they wrap-around. – jamesdlin