Home:ALL Converter>How does volatile work with const?

How does volatile work with const?

Ask Time:2017-08-30T05:10:12         Author:Napstablook

Json Formatter

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.

Author:Napstablook,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/45948381/how-does-volatile-work-with-const
templatetypedef :

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.\n\nIn 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).\n\nIn 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.",
2017-08-29T21:12:42
yy