Alex Rivera | Logout

Making sense of where "const" goes in a declaration

Asked 2011-07-06T02:04:48.080
12

I am having trouble finding an intuitive pattern for the way const is used in declarations in the C and C++ languages. Here are some examples:

const int a;    //Const integer
int const a;    //Const integer
const int * a;  //Pointer to constant integer
int * const a;  //Const pointer to an integer
int const * a const;    //Const pointer to a const integer

In lines 1 and 2, it seems const can come before or after int, which is what it modifies.

  1. So how, in line 4, does the compiler decide that const is modifying * (pointer) rather than int?
  2. What is the rule that the compiler follows for deciding which thing the const applies to?
  3. Does it follow the same rule for *?
Edit
Report

3 Answers

7

Assuming you always place const to the right of the type, you can read a variable declaration as a sentence from right to left:

int const x;        // x is a constant int
int *const x;       // x is a constant pointer to an int
int const *x;       // x is a pointer to a constant int
int const *const x; // x is a constant pointer to a constant int

This still works if you put const to the left of a type, but requires a bit more mental effort. Note that this works just as well with pointers-to-pointers (and higher order constructs):

int *const *const x; // x is a constant pointer to a constant pointer to an int
answered 2011-07-06T02:14:10.500
5

The compiler generally reads the type from right-to-left, so:

T const& const

Would be read as:

 const (a constant)
 & (to a reference)
 const (to a constant)
 T (of type T)

So, basically the keyword "const" modifies everything that precedes it. However, there is an exception in the case where "const" comes first, in which case it modifies the item directly to the right of it:

const T& const

The above is read as:

const (a constant)
& (to a reference)
const T (to a constant of type T)

And the above is equivalent to T const& const.

While this is how the compiler does it, I really just recommend memorizing the cases "T", "const T", "const T&", "const T*", "const T& const", "const T* const", "T& const", and "T* const". You will rarely encounter any other variation of "const", and when you do, it's probably a good idea to use a typedef.

answered 2011-07-06T02:15:25.870
2

For pointers, here's one I picked up from one of Scott Meyers's books (I think). Draw a vertical line through the *, and then whatever's on the same side of the line as the const keyword is the thing that's const.

To clarify:

int * const a means that a is const, not the int. And "a" is a pointer to the (non-const) int.

answered 2011-07-06T02:17:10.163

Your Answer