Dork
Dork

Reputation: 1886

Why can I modify at which char const char * points?

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 ?

Upvotes: 3

Views: 103

Answers (1)

Bathsheba
Bathsheba

Reputation: 234885

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";

Upvotes: 3

Related Questions