Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If you have a variable pointing at another, isn't supposed to change its value sine its replacing the value?
C++
#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;
    cin.get();

    return 0;
}


Output:

d
s
Posted
Updated 25-May-13 12:32pm
v4

The meaning const has been changed:

In C++98: const meant logically const, but as of C++11 const is now thread safe - meaning that it has to be bitwise const. So the compiler is free to rewrite:
cout << c << endl;

as:
cout << 's' << endl;


Bitwise const means that every bit in the object or variable is permanent.

Best regards
Espen Harlinn
 
Share this answer
 
v2
Comments
H.Brydon 26-May-13 22:38pm    
Hey - I didn't know that! +5 from me.
Espen Harlinn 27-May-13 3:23am    
Thank you :-D
Sergey Alexandrovich Kryukov 11-Jun-13 19:46pm    
5ed. I did no know that, too.
—SA
Espen Harlinn 12-Jun-13 15:44pm    
Thank you, Sergey :-D
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:
C++
#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;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900