Click here to Skip to main content
15,867,488 members
Articles / Programming Languages / C
Tip/Trick

Looking at pointer declarations

Rate me:
Please Sign up or sign in to vote.
4.53/5 (9 votes)
12 Jan 2010CPOL 14K   6   3
When we look at pointer declarations, reading from right-to-left gives a better idea about what the pointer actually points to. Consider const int * p; if we read right to left: p -> * -> int -> const. i.e. 'p is a pointer to an integer constant' rather than 'constant integer pointer' (if we...
When we look at pointer declarations, reading from right-to-left gives a better idea about what the pointer actually points to.

Consider const int * p; if we read right to left: p -> * -> int -> const. i.e. 'p is a pointer to an integer constant' rather than 'constant integer pointer' (if we read left to right) which doesn't give an idea if the pointer is constant or the value it is pointing to.

So reading it right to left gives clear idea that in the above declaration, p can be modified (like p++) but the value p is pointing to (*p) cannot be modified as it is pointing to a constant.

Let us consider another example int * const p;. Again let us use the same right-to-left trick, p -> const ->* -> int. i.e. p is a constant pointer to an integer. In this case, p cannot be modified (like p++) but the value it is pointing to can be modified (like *p = 2).

Finally in const int * const p; 'p is a const pointer to an integer constant' by using the same RTL trick.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 So Simple But Good Pin
Global Analyser20-Jun-11 4:31
Global Analyser20-Jun-11 4:31 
Generalnice! Pin
Sir Gizzle10-Feb-10 22:43
Sir Gizzle10-Feb-10 22:43 
Generalfor details look at Pin
Manish K. Agarwal10-Feb-10 19:53
Manish K. Agarwal10-Feb-10 19:53 
How to interpret complex C/C++ declarations[^]
Manish Agarwal
manish.k.agarwal @ gmail DOT com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.