Monday, March 10, 2014

Constant Pointers and pointers to a constant (Ahhh... what was that?)

What do the following declarations mean?


  1. const int a; 
  2. int const a; 
  3. const int *a; 
  4. int * const a; 
  5. int const * a const; (or const int * const a;)


(1 & 2) The first two mean the same thing, namely a is a const (read-only) integer. 

(3) The third means a is a pointer to a const integer (i.e., the integer isn’t modifiable, but the pointer is). 

(4) The fourth declares a to be a const pointer to an integer (i.e., the integer pointed to by a is modifiable, but the pointer is not). 

(5) The final declaration declares a to be a const pointer to a const integer (i.e., neither the integer pointed to by a, nor the pointer itself may be modified).

Why to put so much emphasis on const, since it is very easy to write a correctly functioning program without ever using it. There are several reasons:

1. The use of const conveys some very useful information to someone reading your code. In effect, declaring a parameter const tells the user about its intended usage. If you spend a lot of time cleaning up the mess left by other people, then you’ll quickly learn to appreciate this extra piece of information. (Of course, programmers that use const, rarely leave a  mess for others to clean up…)

2. const has the potential for generating tighter code by giving the optimizer some additional information. 

3. Code that uses const liberally is inherently protected by the compiler against inadvertent coding constructs that result in parameters being changed that should not be. In short, they tend to have fewer bugs.

No comments:

Post a Comment