1

I have this code

int main()
{
    char A = 'E';

    const char * i;

    i = &A;

    A = 'B';

}

which actually compiles with MSVC, why? Isn't a const char * supposed to point to a constant character variable? Why can I change A to 'B' in the last line?

Am I missing something?

Johnny Pauling
  • 12,701
  • 18
  • 65
  • 108

3 Answers3

8

There is a difference between a constant of type char being pointed to (a.k.a. the pointee) and a constant pointer of type char*. If you want to protect a pointer from (accidental) modification, you can declare it constant:

char* p = '...';
char* const cp = 'Hello, World!'; // a constant pointer
cp[1] = ','; // okay, the pointee is not constant
cp = p;      // error, the pointer is constant

A variable pointer to a constant can change:

char *p = '...';
const char* pc = 'Hello, World!'; // pointer to a constant
pc[1] = ','; // error, the pointee is constant
pc = p;      // okay

And finally, you can declare a constant pointer to a constant with

const char* const cpc = 'Hello, World!';
cpc[1] = 'a'; // error, pointee cannot change
cpc = p;      // error, pointer cannot change

This is from §5.4.1 of “The C++ Programming Language”, Stroustrup.

You can change A to 'B' in the last line, because A is of type char and therefore can be changed. It isn’t declared a const char, which would prevent you from doing so.

Lumen
  • 3,554
  • 2
  • 20
  • 33
7

A const char* only prevents you from modifying the pointed-to variable through that pointer. It does not, and indeed, cannot, ever, prevent you from modifying it through other means. const pointers and references would be of little use if they could only point or refer to const values.

Puppy
  • 144,682
  • 38
  • 256
  • 465
4

const char* implies that you can't modify the pointee through this pointer. That doesn't mean someone else won't be able to do it.

slaphappy
  • 6,894
  • 3
  • 34
  • 59