Search code examples
cvolatile

Using volatile qualifier suppresses compiler warning


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:

  1. Which exact gcc flags should I enable to get this warning?
  2. Why declaring i as volatile is suppressing that warning?

Solution

  • When aggressive loop optimization sees the following code...

    int i;
    i=0;
    while(i<5) {
        printf("%d\t", a[i]);
        i+=2;   
    }
    

    ... it's going to use a technique called "loop unrolling" to rewrite it like this...

    printf("%d\t", a[0]);
    printf("%d\t", a[2]);
    printf("%d\t", a[4]);
    

    Problem! Iterations 0 and 1 are fine, but iteration 2 will perform an out-of-bounds array access, invoking undefined behavior. That's why you got the warning you did.

    Declaring i to be volatile prevents the compiler from doing this optimization (because it can't be sure that another process isn't modifying the value of i during loop execution), so it has to leave the code as it was. You still have the undefined behavior, it's just that the compiler doesn't warn you about it. All in all, a terrible "fix" from your co-worker.