0

I am having trouble when using right to left rule to interpret variable declarations when typedef is involved.

In the C++ primer 5th edition book I saw the following code:

typedef char *pstring;
const pstring cstr = 0; // cstr is a constant pointer to char
const pstring *ps; // ps is a pointer to a constant pointer to char

If I replace the pstring with char * then it stands like this:

const char *cstr

So I expect cstr to be a pointer to a const char. But the comments in the book states the pointer itself is constant. My question is what's wrong with my way of thinking.

  • 1
    Your confusion on this is understandable and a good example of why `typedef` should not be abused this way. – Christian Gibbons Apr 01 '19 at 18:32
  • 1
    Reopening. The given dup is talking about the position of `*` as in `char *p` or `char* p`. This question is about `const` when applied to a typedef'ed pointer. – dbush Apr 01 '19 at 18:35
  • Maybe you'll find `typedef char *pstring;` easier to read as `using pstring = char *;` .. – Jesper Juhl Apr 01 '19 at 18:40
  • In addition to Artyer's answer below, it should be noted that the "left-to-right rule" is, unfortunately, not an accurate model for how declarations in C (and C++) actually work. You may want to have a look at, e.g., this: https://stackoverflow.com/questions/51540693/whats-the-syntax-to-bind-reference-to-pointerall-kinds/51540903#51540903 – Michael Kenzel Apr 01 '19 at 18:42

2 Answers2

2

A typedef is not a macro. You don't just text replace it.

Read it as cstr is a "constant pstring", which is a "constant (pointer to char)". Compare this to const char*, which is "pointer to constant char".

If you were to replace the typedef it would look like this:

char* const cstr = 0;
char* const* ps;
Artyer
  • 31,034
  • 3
  • 47
  • 75
1

As can be read here:

If an array type is declared with the const type qualifier (through the use of typedef), the array type is not const-qualified, but its element type is

Because pstring is typedef to char *, const pstring cstr is char * const cstr, not const char * cstr.

Jefferson
  • 529
  • 4
  • 9