The latest gcc 4.7 branch miscompiles the following code on x86_64-linux at -O2 and -O3 in both 32-bit and 64-bit modes. It also affects 4.6.x, but not 4.8.x and the current gcc trunk. The issue seems to be considering signed short and signed char for overflows, but neither overflows. $ gcc-trunk -O2 small.c $ a.out $ gcc-4.8.2 -O2 small.c $ a.out $ gcc-4.7.3 -O2 small.c $ a.out ^C $ gcc-4.7-branch -O2 small.c $ a.out ^C $ gcc-4.7-branch -v Using built-in specs. COLLECT_GCC=gcc-4.7-branch COLLECT_LTO_WRAPPER=/usr/local/gcc47-branch/bin/../libexec/gcc/x86_64-unknown-linux-gnu/4.7.4/lto-wrapper Target: x86_64-unknown-linux-gnu Configured with: ../gcc-4.7/configure --enable-languages=c,c++ Thread model: posix gcc version 4.7.4 20140209 (prerelease) [gcc-4_7-branch revision 207641] (GCC) $ ------------------- short a; int main() { for (; a >= 0; a++) ; return 0; }
Dup of bug 35634. *** This bug has been marked as a duplicate of bug 35634 ***
Note there is no overflow happening here at all. In that a++ is the same as a = a + 1 which is the same as a = (short)(((int)a) + 1) due to promotion rules in C.
Technically there is an overflow there. But GCC defines conversion to a smaller signed integer type, when the value cannot be represented in that smaller type, as a non-signalling truncation. Still, portable code mustn't rely on that.
Well, the conversion is implementation-defined behavior, and GCC documents what it does in that case (does it?) and thus you can rely on it, and given that other compilers also have simimilar implementation-defined behavior choice for that case, you can portably assume it unless you are targetting extinct architectures.