I have a question depending on the location of 'const' in C++

47 Views Asked by At
int i = 0;
int* lv1 = &(++i); //++i is lvalue
//int* rv1 = &(i++); //i++ is rvalue
const int* &rv1 = &i;
int* const &rv2 = &i;
int* &&rv3 = &i;
const int &rv4 = 5;
int const &rv5 = 5;

Why is line 5 not giving an error, but line 4 is an error?

In the case of a reference, I know that the upper const and lower consts are meaningless. Super const means that the variable itself is const, Sub-const means that the variable's value is const. This expression is given in C++ Primer.

1

There are 1 best solutions below

0
Remy Lebeau On

The rule of thumb about const is that it applies to the thing on its left, unless there is nothing there, then it applies to the thing on its right.

On line 4, the const applies to the int only, so const int* &rv1 = &i; is a reference to a non-const pointer to a const int.

On line 5, the const applies to the * only, so int* const &rv2 = &i; is a reference to a const pointer to a non-const int.