gpt4 book ai didi

c - 调用 `volatile`时需要 `longjmp()`?

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:01 25 4
gpt4 key购买 nike

我正在尝试制作一个最小的工作示例来说明何时需要 volatile。但是下面的例子不需要volatile。有人可以举个例子吗?谢谢。

#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

最佳答案

每当局部变量可能在对 setjmp 的设置调用和跳回之间发生变化时。

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 快照您的寄存器。如果局部变量在寄存器中,并且您在 setjmp 调用之后更改了该变量,那么当您返回时,它将具有快照值。

在 Linux x86_64 上,我得到输出 2(因为不稳定,所以是最新的)和 10(旧值),前提是我编译时启用了优化。

关于c - 调用 `volatile`时需要 `longjmp()`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com