Navjot Singh
Navjot Singh

Reputation: 696

Why it is a const pointer rather than pointer to const?

In C++ Primer book, there is an explanation on type aliases as:

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

They say that the following is a wrong interpretation:

const char *cstr = 0;

However it makes sense to me, to replace the typedef alias with its original meaning.

In a normal scenario without type aliasing a constant pointer is defined as:

char *const cstr = 0;

Why is it constant pointer rather than pointer to const?

Can anyone explain in clear terms because the book doesn't seem to clarify it much.

Upvotes: 0

Views: 84

Answers (1)

2 * 3 + 1 is 7. But how come if I do int i = 3 + 1; and then 2 * i it gives 8? Shouldn't the variable be replaced with its original meaning?

It's because 2 * 3 + 1 is interpreted as (2 * 3) + 1, while 2 * i is the same as 2 * (3 + 1). These mean different things and work out to different numbers. When you give 3 + 1 a name, when you use the name it doesn't break up the number back into 3 + 1 in order to only multiply the 3.

The reason that const char * is different from const pstring is very similar. const char * is interpreted as (const char) * i.e. a pointer to a constant char. But const pstring is the same as const (char *) i.e. a constant pointer to a char. pstring is a whole type by itself, and when you do const pstring it doesn't split up the char * in order to make the char part const.

Note: if you did #define pstring char * then const pstring would be the same as const char *, because macros (#defines) are just treated as text replacements.

Upvotes: 2

Related Questions