Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of constexpr and const in reference definition

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?

like image 968
Jayesh Avatar asked Apr 21 '17 05:04

Jayesh


People also ask

Should I use const with constexpr?

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.

When to use #define vs constexpr?

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

Where is constexpr defined?

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.

What is constexpr keyword in C++?

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.


1 Answers

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

like image 176
ralismark Avatar answered Oct 11 '22 14:10

ralismark