Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Looking at pointer declarations

4.53/5 (9 votes)
12 Jan 2010CPOL 15K  
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)