On Wed, 09 Oct 2013, vijay nag wrote: > Hello GCC, > > I'm facing a wierd compiler optimization problem. Consider the code > snippet below > > #include <stdio.h> > > int printChar(unsigned long cur_col, unsigned char c) > { > char buf[256]; > char* bufp = buf; > char cnt = sizeof(buf) - 2; /* overflow in implicit type conversion */ > unsigned long terminal_width = 500; > > while ((cur_col++ < terminal_width) && cnt) { > *bufp++ = c; > cnt--; > } > > *bufp++ = '\n'; > *bufp = 0; > > printf("%c\n", buf[0]); > return 1; > } > > int main() > { > printChar(80, '-'); > return 1; > } > > While compiler optimization should guarantee that the result of > execution is same at all optimization levels, I'm observing difference > in the result of execution of the above program when optimized to > different levels. Although there is fundamental problem with the > statement "char cnt = sizeof(buf) - 2", GCC seems to be warning(that > too only when -pedantic flag is used) about overflow error while > silently discarding any code related to cnt i.e. the check "&& cnt" in > the if-clause is silently discarded by the compiler at -O2. > > $]gcc -g char.c -o char.c.unoptimized -m32 -O0 -Wall -Wextra -pedantic > char.c: In function ?printChar?: > char.c:8: warning: overflow in implicit constant conversion > This compiler optimization dependency is visible with quite a few code examples that violate the C standard. Integer overflow/underflow results in undefined behavior - you are in the wild lands basically - you should not expect C-standard violations to result in "reliable undefined" code. See C99 Annex J.2 for details of undefined behaviors. thx! hofrat