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?
const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.
#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.
constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time. The key point of constexpr is that it can be executed at compile time.
The constexpr keyword, short for constant expression, was a feature introduced in C++11 that allows the value of an expression to be evaluated at compile-time.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With