Is const char* a string or a mutable pointer

  • A+
Category:Languages

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: