0

If I have to assign a pointer to constant char or int variable, what is the difference between the following assignments:

char x{'a'}; // declare and initialise a char variable
const char *p = &x; // assign the address of the char to constant pointer

But the following doesn't compile:

const char x{'a'};
char *p = &x; // assign the address of the constant char to non-constant pointer

This produces an error: invalid conversion from ‘const char*’ to ‘char*’

I am missing something in understanding this behaviour.

rustyhu
  • 1,912
  • 19
  • 28
Ananth
  • 55
  • 1
  • 8
  • [This question](https://stackoverflow.com/questions/21476869/constant-pointer-vs-pointer-to-constant) explains some of it. In the first code snippet, `p` itself is non-`const`, but it is pointing to a `const char`. You can change `p` to point at a different location, but you cannot change `*p`. In the second snippet, `p` is a non-`const` pointer to a non-`const` `char`, which contradicts the declaration that `x` itself is a `const char`. – Nathan Pierson Dec 08 '20 at 05:57
  • 1
    The address of a variable is constant, so the expression `&x` results in a `const` pointer. – jkb Dec 08 '20 at 05:57

0 Answers0