Reputation:
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.
Upvotes: 0
Views: 354
Reputation: 529
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
.
Upvotes: 1
Reputation: 40826
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;
Upvotes: 2