如何在不知道的情况下更改变量的值?
我想通过这个方法来验证一下 volatile 的作用。但我的内联汇编代码似乎无法在编译器不知道的情况下修改 i 的值。根据我看的文章,我只需要写像 __asm { mov dword ptr [ebp-4], 20h }
这样的汇编代码,我想我写的和他做的一样。
实际输出:
before = 10
after = 123
预期输出:
before = 10
after = 10
文章链接: https://www.runoob.com /w3cnote/c-volatile-keyword.html
#include <stdio.h>
int main() {
int a, b;
// volatile int i = 10;
int i = 10;
a = i;
printf("before = %d\n", a);
// Change the value of i in memory without letting the compiler know.
// I can't run the following statement here, so I wrote one myself
// mov dword ptr [ebp-4], 20h
asm("movl $123, -12(%rbp)");
b = i;
printf("after = %d\n", b);
}
I want to verify the role of volatile by this method. But my inline assembly code doesn't seem to be able to modify the value of i without the compiler knowing. According to the articles I read, I only need to write assembly code like __asm { mov dword ptr [ebp-4], 20h }
, I think I write the same as what he did.
actual output:
before = 10
after = 123
expected output:
before = 10
after = 10
Article link: https://www.runoob.com/w3cnote/c-volatile-keyword.html
#include <stdio.h>
int main() {
int a, b;
// volatile int i = 10;
int i = 10;
a = i;
printf("before = %d\n", a);
// Change the value of i in memory without letting the compiler know.
// I can't run the following statement here, so I wrote one myself
// mov dword ptr [ebp-4], 20h
asm("movl $123, -12(%rbp)");
b = i;
printf("after = %d\n", b);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能。
如果变量不是
挥发性
,则编译器 May Optimize;它确实不需要来做到这一点。编译器可以始终将任何变量视为
volatile
。创建第二个线程写入变量。
示例
以下示例用于Linux(在Windows下,您需要一个与
pthread_create()
)不同的功能:如果您使用
gcc -o0 -ox XC-编译lpthread
,编译器不会优化,并且像所有变量一样volatile
。printf()
打印113。如果您使用
-O3
而不是-O0
,printf()
打印0 。/
-O3
)。(使用GCC 9.4.0编译器进行测试。)
You can't.
If a variable is not
volatile
, the compiler may optimize; it does not need to do this.A compiler may always treat any variable as
volatile
.Create a second thread writing to the variable.
Example
The following example is for Linux (under Windows, you need a different function than
pthread_create()
):If you compile with
gcc -O0 -o x x.c -lpthread
, the compiler does not optimize and works like all variables arevolatile
.printf()
prints 113.If you compile with
-O3
instead of-O0
,printf()
prints 0.If you replace
int testVar
byvolatile int testVar
,printf()
always prints 113 (independent of-O0
/-O3
).(Tested with the GCC 9.4.0 compiler.)