Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is const char* a string or a pointer

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?

like image 583
W.Joe Avatar asked Dec 14 '22 17:12

W.Joe


2 Answers

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

like image 158
StoryTeller - Unslander Monica Avatar answered Jan 08 '23 15:01

StoryTeller - Unslander Monica


It's a pointer and by assigning it to "John", you make it point to another case memory where "John" starts.

like image 25
Sébastien S. Avatar answered Jan 08 '23 14:01

Sébastien S.