Reputation: 13675
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
Reputation: 60068
Whenever the local variable could have changed between the setup-call to setjmp
and the jump back.
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