5

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!

9
  • 4
    In c++ i can write const int const* for a constant pointer to an int. No, thats a duplicate const for the int and none for the pointer. Commented Feb 27, 2019 at 16:39
  • Please separate your code from the text, it is not clear what types you try to create here Commented Feb 27, 2019 at 16:39
  • The difference is that you can write const int & but you can't write const int const &. Commented Feb 27, 2019 at 16:41
  • @tkausl yes i meant const int const* for const int Commented Feb 27, 2019 at 16:41
  • @Francois you can it wont create an error! Commented Feb 27, 2019 at 16:41

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

It seems that OP's compiler does not actually yell at them for that (though I'm pretty sure you're right, and it should).
At Vs2017 and C++ 17 i didnt get an error :/ But ty
Then instead of your compiler yelling at you, you should yell at your compiler.
@xX_EASYHDLPMCAWPGOD_Xx If you disable language extensions with /Za you will get an error (example) though you should still be seeing a warning without it.
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.