4

In c++ i can write const int const* for a constant pointer to an constant int. I can also write const int& for a const reference. So is const int const& a reference to a const int?

Thanks in advance!

3 Answers3

8

const int const* is not a constant pointer to a constant int. To get that you need

const int * const.

In your case you apply both const to the int so you have a mutable pointer to a constant int.

The same thing happen to const int const&. To make a constant reference to a constant int you would need

const int & const

but that is illegal.

Do note that in both const int const* and const int const& it's not actually legal to apply const twice like that.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
5

So is const int const& a reference to a const int?

No, that's a compilation error.

Try compiling something like :

int z = 0;
const int const& a= z;

And you'll see the compiler will yell at you.

You can't duplicate const for the same type. Your premise that const int const* is a constant pointer to a constant int is wrong too.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
3

It is always a good idea to read it backwards as suggested by the Clockwise/Spiral rule if you get stuck in understanding such declarations.

int const *    // pointer to const int
int * const    // const pointer to int
int const * const   // const pointer to const int
int * const * p3;   // pointer to const pointer to int
const int * const * p4;       // pointer to const pointer to const int
Naumann
  • 357
  • 2
  • 13