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?

2

1 Answer 1

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).

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

10 Comments

"which means that the const is redundant" Hardly.
Unless memory fails me, since C++14 constexpr no longer implies const.
@AndyProwl That's for member functions.
Try removing const from the code in the question. It won't compile.
@M.M Obviously you can drop the const if you also change the initializer. My point stands: the answer was wrong to say the const was redundant, as removing the const changed the meaning.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.