// Shift operation yielded different results on different // level of optimization for the same source. O1 is working but // not O2 and O3 // Tested environments: Fedora 10. GCC 4.3.2.20081105 // and Windows XP, MingGW GCC 4.5.2 // Compiler output and warning: nothing // source file: one attached (no header file) #include "stdio.h" /* * Incorrect -O2 and -O3 optimization for 64 bit integer shift operator. * -O1 is working correclty g++ -O1 main.cpp && ./a.out i[0]=0, i[1]=8 g++ -O2 main.cpp && ./a.out i[0]=1, i[1]=0 g++ -O3 main.cpp && ./a.out i[0]=1, i[1]=0 */ int main(int argc, char* argv[]) { int i[2]; i[0] = 1; i[1] = 0; *((unsigned long long *) (&i)) <<= 35; /* correct result: linux test i[0]=0, i[1]=8 */ printf ("i[0]=%d, i[1]=%d\n", i[0],i[1]); return 0; }
Created attachment 24463 [details] Added attachment for the last commitment
This is aliasing violation, the code has undefined behavior.
I've tried GCC 4.6 (r174793, i786-pc-mingw32) and it gives the 'corrent' result (-01 -02 or -03): i[0]=0, i[1]=8