Example program works with option -O1, but not with -O2 Problem occurs with gcc 4.3.2 and 4.4.0, but not with 4.2.4 Environment: System: Linux andiunx 2.6.27-11-generic #1 SMP Fri Dec 19 16:29:52 UTC 2008 i686 GNU/Linux host: i686-pc-linux-gnu build: i686-pc-linux-gnu target: i686-pc-linux-gnu configured with: ./configure How-To-Repeat: Compile the following program with gcc -O2 foobar.c extern int printf (__const char *__restrict __format, ...); int main () { int j; for (j = 1; j > 0; j += j) printf("%d\n",j); return 0; }
Fix: Do not use -O2 option.
This code is undefined as you would have an integer overflow which is undefined by both the C and C++ standards. You can use -fwrapv for wrapping of signed integers or cast to unsigned before doing the addition.