Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to typedef a constant variable

Tags:

c

typedef

  typedef char* ptr;
  const ptr p;

Which is true:

  • p points to a constant character; or
  • p is a constant and points to a character.

Please explain the reason

like image 487
sourabh912 Avatar asked Dec 12 '22 00:12

sourabh912


2 Answers

typedef char* ptr;
const ptr p;

The latter line is equivalent to

char * const p;

i.e. p is a const pointer to char. The typedef introduces a new name for a type, it is not a textual substitution.

like image 173
Daniel Fischer Avatar answered Jan 03 '23 20:01

Daniel Fischer


First, let's take the typedef out of the equation for a moment.

const char *p and char const *p both declare p as a non-const pointer to const data; you can assign p to point to different things, but you cannot modify the thing being pointed to.

char * const p declares p as a const pointer to non-const data; you cannot change p to point to a different object, but you can modify the thing p is pointing to.

const char * const p and char const * const p both declare p as a const pointer to const data. That should be fairly self-explanatory.

The typedef is a little non-intuitive. ptr is a synonym for char *, so const ptr acts as char * const; the const qualifier is being applied to the pointer type, not the char type.

like image 42
John Bode Avatar answered Jan 03 '23 19:01

John Bode