Today I was reviewing a guys's code where he had declared a variable volatile. On asking about it, he told it produces weird behaviour on some systems.
On removing volatile and compiling, it was producing this compiler warning
iteration 2 invokes undefined behavior [-Waggressive-loop-optimizations]
The code was very much similar to the below code, array being accessed out of bound. Since he was using a different codebase where Makefile was different, this warning was not produced on his system.
int a[4]={1,2,3,4};
int i; //when declared volatile int i, doesn't produce warning
i=0;
while(i<5) {
printf("%d\t", a[i]); //a[4] will invoke undefined behavior
i+=2;
}
Now, I'm unable to figure out two things:
- Which exact gcc flags should I enable to get this warning?
- Why declaring
ias volatile is suppressing that warning?