Why the compiler can not recognize what variables are volatile?

Peng Yu pengyu.ut@gmail.com
Thu Feb 7 00:44:00 GMT 2019


Hi,

If I compile the following program without -O*, it will print this.

$ ./main.exe
2
20

If I compile it with -O1 or any other number > 1, it will print this.

$ ./main.exe
2
10

The optimization clearly changes the semantics of the program. Why the
compiler can not figure out local_var2 is volatile on its own to
reduce the burdens of the programmers in having to figure out what
variables should be specified as volatile?

Thanks.

#include <stdio.h>
#include <setjmp.h>

static jmp_buf buf;

int main() {
    volatile int local_var = 1;
    int local_var2 = 10;
    if(!setjmp(buf)) {
        local_var = 2;
        local_var2 = 20;
        longjmp(buf, 1);
    } else {
        printf("%d\n", local_var);
        printf("%d\n", local_var2);
    }

    return 0;
}

-- 
Regards,
Peng



More information about the Gcc-help mailing list