According to the
documentation[
^]:
Depending on the type of the referenced object, a write operation through the resulting pointer, reference, or pointer to data member might produce undefined behavior.
Because
c
is a
const char
variable the compiler is probably saving the value in a CPU register, not expecting it to change so it never actual re-reads it from memory. The result is the behaviour you are seeing.
Try this:
#include <iostream>
using namespace std;
void print (char * str)
{
*str = 'd';
cout << *str << endl;
}
int main(void)
{
const char c = 's';
print(const_cast<char*>(&c));
cout << c << endl;
cout << *(const_cast<volatile char *>(&c)) << endl;
cout << c << endl;
cin.get();
return 0;
}