This snippet of code should demonstrate my problem. GCC's optimization level of 0 will make this perform as expected: that is, any trailing newlines get removed. But at any higher optimization levels, GCC seems to decide that the assignment to zero is unnecessary, and vanishes it away.Code:#include <stdio.h> #include <string.h> #define BUFFLENGTH 100 int main() { char buffer[BUFFLENGTH+1]; memset(buffer,0,BUFFLENGTH+1); fgets(buffer,BUFFLENGTH,stdin); buffer[strcspn(buffer,"\n")] = 0; printf("%s.\n",buffer); return 0; }
I can, of course, make "buffer" a volatile char array, but in my real code (this is just a simplified version for clarity), GCC complains with a warning whenever I try to use "buffer" for anything else; e.g. passing it to a function, unless I re-cast it to a char * or const char *. I know of no reason why I shouldn't cast like this (to my understanding, a volatile char is the same size as a char, just treated differently by the compiler), but doing this for each invocation of "buffer" seems both annoying and ugly.
Is there any other way I can hint to GCC not to optimize this specific statement?