I thought const char* represents a mutable pointer to an immutable string.
However, when I do this,
#include <iostream>
using namespace std;
const char *name1 = "Alex";
int main()
{
name1 = "John";
cout << name1 << endl;
}
it just prints John and shows no problems. I wonder why the program treats name1 as a string and makes it mutable?
I wonder why the program treats name1 as a string and makes it mutable?
It doesn't, you just assigned a new address to the pointer (the address of "John"
). You said it yourself "a mutable pointer to an immutable string". You modified the pointer, and had you tried to actually modify the pointee, the type system would have prevented you from doing that (on account of the const qualifier).
It's a pointer and by assigning it to "John", you make it point to another case memory where "John" starts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With