How does volatile work with const?

夙愿已清 提交于 2020-07-04 04:27:11

问题


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);

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);

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.


回答1:


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.

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 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.




回答2:


The compiler doesn't warn you about c-style casts:

int *ptr = (int*)&local;

this:

*ptr = 100;

is undefined behavior.

All of that doesn't have to do with volatile at all.



来源:https://stackoverflow.com/questions/45948381/how-does-volatile-work-with-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!