我使用 gcc 4.8.4 和 -O0 标志编译了以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
static jmp_buf env;
static void
doJump(int nvar, int rvar, int vvar)
{
printf("Inside doJump(): nvar=%d rvar=%d vvar=%d\n", nvar, rvar, vvar);
longjmp(env, 1);
}
int
main(int argc, char *argv[])
{
int nvar;
register int rvar;
volatile int vvar;
nvar = 111;
rvar = 222;
vvar = 333;
if (setjmp(env) == 0) {
nvar = 777;
rvar = 888;
vvar = 999;
doJump(nvar, rvar, vvar);
} else {
printf("After longjmp(): nvar=%d rvar=%d vvar=%d\n", nvar, rvar, vvar);
}
exit(EXIT_SUCCESS);
}
它产生了以下输出:
Inside doJump(): nvar=777 rvar=888 vvar=999
After longjmp(): nvar=777 rvar=222 vvar=999
我的预期是 rvar 将在第二行中为 888,因为所有优化都已禁用。
当我从 'rvar' 的定义中删除 'register' 或当我在 'register' 前面添加 'volatile' 时,它输出 888。
因此尽管有 -O0 标志,gcc 似乎仍然执行一些优化。
有没有办法完全禁用 gcc 中的所有优化?
最佳答案
C11 标准对 longjmp()
说:
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 correspondingsetjmp
macro that do not have volatile-qualified type and have been changed between thesetjmp
invocation andlongjmp
call are indeterminate.249) This includes, but is not limited to, the floating-point status flags and the state of open files.
您遇到了不确定的值...符合标准的行为。
关于c - 为什么 gcc 使用 -O0 进行一些优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906896/