volatile如何与const一起工作? [英] How does volatile work with const?

查看:77
本文介绍了volatile如何与const一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,照例,变量 local的值保持不变,因为它是 const

I have this code where as usual, value of the variable "local" stays the same cause it is a const.

const int local = 10;
int *ptr = (int*)&local;
printf("Initial value of local : %d \n", local);
*ptr = 100;
printf("Modified value of local: %d \n", local);

尽管,当我将local设置为 const volatile 时,它会更改值到100的本地货币。为什么?

Although, when I set local as const volatile, It changes the value of local to 100. Why is that?

const volatile int local = 10;
int *ptr = (int*)&local;
printf("Initial value of local : %d \n", local);
*ptr = 100;
printf("Modified value of local: %d \n", local);

我了解的volatile的唯一含义是,它阻止了编译器对该变量进行优化,以防万一其值必须由外部元素更改。但是我无法弄清楚 volatile 为何以及为何会覆盖 const 的功能。

The only meaning of volatile that I understand is that it prevents the compiler from doing optimization for that variable, just in case its value has to be changed by an outside element. But I cannot figure out how and why is volatile overriding the features of const.

编辑-从我的代码模棱两可且所有输出都是不可预测的所有答案,原因是我正在调用未定义的行为。

EDIT- It seems from all the answers that my code was ambiguous and any output is unpredictable cause I was invoking undefined behavior.

推荐答案

在C ++中,更改通过指针声明为const的对象的值-就像您在此处所做的一样-导致未定义的行为,这意味着绝对会发生任何事情,并且您所看到的一切都无法保证。

In C++, changing the value of an object that was declared const through a pointer - like what you're doing here - leads to undefined behavior, meaning that absolutely anything can happen and there are no guarantees at all about what you'll see.

在这种情况下,您看到了存储在const变量中的原始值,但是很容易又回来显示了另一个值。我的猜测是,编译器识别出该变量是const,将其缓存起来,然后将其硬编码到程序集中(尽管我不确定)。

In the first case, you saw the original value that was stored in the const variable, but that could just as easily have come back showing a different value. My guess is that the compiler recognized that the variable was const, cached the value, and then hardcoded it into the assembly (though I can't be sure).

In第二种情况,我的猜测是编译器认识到该变量是易失性的,因此没有缓存内容,因为它无法假定程序外部的某些内容会更改该值。但是,您仍然不能认为这可以在多个编译器或操作系统上使用。

In the second case, my guess is that the compiler recognized that the variable was volatile and therefore didn't cache things because it couldn't assume that something external to the program would change the value. However, you still can't assume this will work across multiple compilers or operating systems.

这篇关于volatile如何与const一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆