7

I have seen declaring a reference variable as constant in C++ on Quora.

static constexpr const int& r = 3;

So, Why both constexpr and const used in single statement?

What is the purpose of that type of statement?

Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • Useful reading: http://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const What is the purpose? Demonstration, I think. – user4581301 Apr 21 '17 at 05:42
  • 4
    Similar question, http://stackoverflow.com/questions/28614591/how-to-initialize-a-constexpr-reference. `constexpr` applies to the reference and `const int` is the thing referred to, they have different meanings – M.M Apr 21 '17 at 05:58

1 Answers1

6

const variables are ones that cannot be modified after initialisation (e.g. const int a = 1).

constexpr variables are constant expressions and can be used at compile-time. The use of constexpr for a variable declaration implies const.

However, in this declaration, const applies to the int, while constexpr applies to const int& (a reference to a const int).

ralismark
  • 746
  • 9
  • 24