3

I'm learning const and pointers playing with examples. From this thread I read that: const char* the_string : I can change the char to which the_string points, but I cannot modify the char at which it points.

 int main()
{
    const char* a = "test";
    char* b = "other";
    a = b;
    cout << a << endl; //prints "other"
}

Why can I modify at which char a points ?

Community
  • 1
  • 1
Dork
  • 1,816
  • 9
  • 29
  • 57
  • `a` is a pointer. It is used to refer to some data (in this case, a `char` array). Pointers are separate entities from the data they point to, so they often become a source of confusion regarding whether we're talking about the pointer or the data. In this case, `const` refers to the *data*. It doesn't have to refer to the pointer as well. – Theodoros Chatzigiannakis Nov 11 '16 at 15:42
  • Why reopen this question? This is the exact same question as the linked question, and the linked question has good answers. – Barry Nov 11 '16 at 15:49
  • I did. @Barry you're possibly one of the smartest guys on this site, if not *the* smartest, so things that are obvious to you are possibly not to other folk. I didn't think that duplicate was "obvious" enough for a gold hammer. – Bathsheba Nov 11 '16 at 15:59
  • @Bathsheba Ha. I don't know how to respond to that. I'm definitely not one of the smartest guys on this site. – Barry Nov 11 '16 at 16:18

1 Answers1

3

You can set a to point at something else since a is itself not const: only the data to which it points is const.

Setting b = a would not be allowed, since you'd be casting away const.

If you want to prevent a = b then write

const char* const a = "test";

Bathsheba
  • 231,907
  • 34
  • 361
  • 483