4

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?

W.Joe
  • 335
  • 2
  • 8
  • 1
    It's a "string" in the "array of characters, zero terminated" sense, not in the `std::string` sense. The pointer is mutable. To make a const pointer, `const char * const name1 = "Alex";`. – Eljay Apr 15 '18 at 10:13

5 Answers5

5

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

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • 1
    Actually, its a mutable pointer to an immutable character which is part of a character array located in the text part of your executable. – JVApen Apr 15 '18 at 10:27
3

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

Sébastien S.
  • 1,444
  • 8
  • 14
2
  • It is a pointer
  • A pointer is an adress in memory.
  • Here you reassign the adress of "John" to name1.
  • cout knows how to print a char * so you see things correctly.

There are no string object in the program

Gabriel
  • 3,564
  • 1
  • 27
  • 49
2

Just for illustration/comparison (in addition to the answers given already): the counter example...

const char *name1 = "Alex";

int main() 
{
    name1[0] = 'J';
    name1[1] = 'o';
    name1[2] = 'h';
    name1[3] = 'n';
    std::cout << name1 << std::endl;
    return 0;
}

Now you do attempt to really modify the immutable string. Luckily, the compiler detects it and prevents you from doing so! const_cast<char>(name[x]) = y; would be next attempt. Looks like fooling the compiler, actually, you fool yourself only by lying and in consequence running into undefined behaviour!

Actually, casting const away is almost always a bad idea (but is legal, if and only if the pointer holds the address of some originally non-constly created memory).

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

I wonder why the program treats name1 as a string and makes it mutable?

Heed the sequence of const in comparison to *. If you want to disallow a rebinding of name1, use char * const. See also What is the difference between const int*, const int * const, and int const *?

Furthermore, const is not about a value being immutable, but about an immutable binding.

Roi Danton
  • 7,933
  • 6
  • 68
  • 80