user1424739
user1424739

Reputation: 13675

When `volatile` is needed when `longjmp()` is called?

I am trying to make a minimal working example to show when volatile is needed. But the following example does not require the volatile. Could anybody show an example? 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;
}
$ ./main.exe 
2
20

Upvotes: 1

Views: 305

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60068

Whenever the local variable could have changed between the setup-call to setjmp and the jump back.

7.13.2.1p3

All accessible objects have values, and all other components of the abstract machine249) have state, as of the time the longjmp function was called, except that the values of objects of automatic storage duration that are local to the function containing the invocation of the corresponding setjmp macro that do not have volatile-qualified type and have been changed between the setjmp invocation and longjmp call are indeterminate.

setjmp snapshots your registers. If the local variable was in a register and you change the variable after the setjmp call, when you jump back it'll have the snapshotted value.

On Linux x86_64 I get outputs 2 (up to date because volatile) and 10 (old value) iff I compile with optimization on.

Upvotes: 1

Related Questions