-1

I have the below simple codes:

constexpr int x = 1;
constexpr int &y = x; -- error. qualifiers dropped in binding reference of type "int &" to intializer of type "const int"

Question:
Why reference y is not a const int &? According to C++ Primer 5th Ed section 2.4.4 (constexpr Variables), all constexpr variable are implicitly const.

Thanks.

yapkm01
  • 3,590
  • 7
  • 37
  • 62
  • Do you know why `constexpr int *` is a constant pointer to a non-const integer, rather than a pointer to a constant integer? – JaMiT Sep 11 '21 at 21:03
  • Not really. Why does it not apply to reference? – yapkm01 Sep 11 '21 at 21:11
  • 1
    Did you read the proposed duplicate? Not only does it also use _C++ Primer 5th Edition_ section 2.44 as a reference, but also comment 2 notes an error message that is equivalent to yours, and asks why the constexpr did not "implicitly 'const'" a variable declared as `constexpr int &`. Pretty close match to your question, no? – JaMiT Sep 11 '21 at 21:24
  • Got it!! That was the very same question raised by me. LOLI guess sometimes it takes a while to sink in. It was "constexpr refers to the object and not the type" statement which helped me.. Thx – yapkm01 Sep 11 '21 at 21:47
  • 1 more question based on the discussion in the link. If constexpr is referring to the object as explained in the link, why is constexpr int x=1; having type .. const int and not int? constexpr int x=1 clearly changes the type – yapkm01 Sep 11 '21 at 22:07
  • In addition to referring to the object, `constexpr` *also* modifies the type by adding a `const`. Since it is the object that is referred to, the `const` goes as close to the object as it can while still being in the type. When you see `constexpr type variable`, read it as `type const variable`. Remove `constexpr` from the left and add `const` to the right. So `constexpr int` -> `int const` while `constexpr int *` -> `int * const` and `constexpr int &` -> `int & const` (which is equivalent to simply `int &` since references cannot be reseated). – JaMiT Sep 11 '21 at 22:28

1 Answers1

2

const int & is not a "const reference to int", strictly speaking. It's a "reference to const int".

Unlike pointers, references can never be const. Even though they can't be modified to point to a different object, they are never considered const.

constexpr adds constness only at the top level. For example, constexpr int *x creates a variable of type int *const (const pointer to int), as opposed to const int * (pointer to const int).

Since references can't be const, the constness implied by constexpr is ignored, and the resulting type is just int &.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207