by geofft · 10y ago · 0 comments
However, the compiler might do something to your program's control flow long before it hits the CPU's arithmetic instructions. For instance, try compiling this function under optimization:
titan:/tmp geofft$ cat test.c
int test(int x) {
if (x > 0) return 1;
x -= 10;
if (x > 0) {
return 2;
}
return 1;
}
titan:/tmp geofft$ cc -O3 -c test.c
titan:/tmp geofft$ objdump -S test.o
test.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <test>:
0: b8 01 00 00 00 mov $0x1,%eax
5: c3 retq
The compiler makes no promises about what happens in the case of signed integer overflow or underflow. In this case, for numbers in [INT_MIN, INT_MIN + 10), it doesn't promise that wrapping happens -- even though, if it were to actually do the math on my CPU, it would end up with two's complement. So it assumes the second if can never be true if the first if is untrue, and optimizes the function to return a constant 1.I think you're right that the phrasing is sloppy, and should be "Signed integers are not allowed to overflow or underflow in C and C++," making it an obligation on the programmer not to overflow. If you're interpreting it as an obligation on the compiler not to implement wrapping, then yeah, that's incorrect.
titan:/tmp geofft$ cc -O3 -c test.c
Is your use of 'cc' instead of 'gcc' intentional here? It implies that all compilers make this "optimization", but I think it's currently only GCC. ICC, Clang, and MSVC continue to work that way that the programmer intended: Godbolt for ICC and Clang http://goo.gl/jFfvyz, MSVC http://webcompiler.cloudapp.net/.While it would be unwise to rely on this "polite" behavior from a compiler, I find it difficult to argue that GCC does a better job of compiling this particular code. But perhaps the speedup on similar code is enough to justify the occasional insidious bug?
It would be nice if there was a GCC option that produced a warning here. Is there one?
Looks like gcc -Wstrict-overflow=3 or higher produces a warning. Alternatively, -fno-strict-overflow disables the optimization (which is included as part of -O2 or higher).
More people should know that the second if statement is unreachable code.