How typedef is constant

typedef char* ptr; const ptr p; 

What is true:

  • p indicates a constant character; or
  • p is a constant and indicates a character.

Please explain the reason.

+4
source share
2 answers
 typedef char* ptr; const ptr p; 

The last line is equivalent

 char * const p; 

i.e. p is a const pointer to char . typedef introduces a new name for the type; it is not text substitution.

+8
source

First, take a typedef from the equation for a moment.

const char *p and char const *p declare p as a non-constant pointer to const data; you can assign p to point out different things, but you cannot change the item that it points to.

char * const p declares p as a constant pointer to non-constant data; you cannot change p to point to another object, but you can change the object pointed to by p .

const char * const p and char const * const p declare p as a constant pointer to const data. This should be reasonably clear.

typedef bit unintuitive. ptr is synonymous with char * , so const ptr acts like char * const ; the const qualifier is applied to the pointer type, not to the char type.

+5
source

All Articles