See the testcase. bar starts as -1, but should be 42 after calling foo(), even though its const. You could argue that bar shouldn't be const since we are modifying it, but even so, the behavior should not be different at -O0 than -O1/2. # gcc quux.c -O0 -o quux # ./quux Success: bar is 42 # gcc quux.c -O2 -o quux # ./quux Error: bar is not 42! (it is -1) Testcase: #include <stdarg.h> #include <stdio.h> void foo (int n_args, ...) { va_list qux; int *bar; va_start (qux, n_args); bar = va_arg (qux, int *); *bar = 42; va_end(qux); } int main (int argc, char **argv) { const int bar = -1; foo (1, &bar); if (bar != 42) printf ("Error: bar is not 42! (it is %d)\n", bar); else printf ("Success: bar is 42\n"); return 0; }
Testcase fails at -O1 and -O2 on both: gcc-4.0.0-13 gcc-4.0.1-2
The testcase is simply invalid, you must not modify a const variable. The compiler is free to assume it is not modified (that is the purpose of the const modifier, right?), but does not have to. You simply trigger an undefined behaviour and anything can happen at that point.