Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sense of where "const" goes in a declaration

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 *?
like image 219
Adam S Avatar asked Jul 06 '11 02:07

Adam S


2 Answers

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
like image 81
Michael Koval Avatar answered Oct 27 '22 13:10

Michael Koval


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.

like image 34
Michael Aaron Safyan Avatar answered Oct 27 '22 15:10

Michael Aaron Safyan