Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointers and typedefs

Status
Not open for further replies.

txiko

Programmer
Apr 26, 2008
1
0
0
GB
Hi there,

I have been struggling for the last days trying to understand one statement made in the book I am reading at the moment (C++ Primer, 5th Ed, page 129)

It tries to explain pointers and typedefs and, for that, gives this bit of code:

typedef string *pstring;
const pstring cstr;

Saying (literally) then: "...what is the type of cstr? The simple answer is that it is a pointer to a const pstring...". After some explanation it concludes then that cstr is a const pointer to a string as well.

OK, I understand at the end cstr is a const pointer to a string (wasn't easy but finally got it), but honestly don't understand why it says it is a pointer to const pstring (note pstring and not strng)...why?? where does the pointer to a pstring come from??

If you could please help me I would be very pleased.
Thanks a lot indeed!!
 
> The simple answer is that it is a pointer to a const pstring
Simple, but wrong.

cstr is a const pstring
Within the declaration itself, there is no pointer, so saying that it's a "pointer to" is just wrong.

But then you have to look back to discover that pstring is really [tt]string*[/tt], at which point it becomes clear that cstr is a [tt]const string *[/tt]

Sure, the fully resolved declaration is that cstr is a pointer to a const string.

> cstr is a const pointer to a string as well.
Careful, "const pointer" and "pointer to const" are both valid terms, but they don't mean the same thing.
Code:
char * const p = &mychar; // const pointer to (variable) char
*p = 'a';  // modifying what it points at is valid
[red]p = &anotherchar; // modifying where it points is not.[/red]
vs.
Code:
const char *p = &mychar; // (variable) pointer to a const char
[red]*p = 'a';  // modifying what it points at is invalid[/red]
p = &anotherchar; // modifying where it points is fine.
Equally, you can apply the 'const' qualifier to the "pointer" and the "pointee".


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top