Member-only story
C++ constexpr: What It Really Is?
Avoid beginner’s mistakes by understanding what is constexpr and how it differs from const in C++
Overview
The constexpr
specifier was introduced in C++11
, for beginners it is confusing because it is similar to the const
qualifier.
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. Your code may have been executed before you run it. That’s the main point.
We can use constexpr
on variables, functions — including constructors, and if statements. We will see the details in the following sections.
Variables
I have written all the details about const
qualifier in another article:
We use the const
qualifier to express our intention to compilers and other programmers that we want the variable to be read-only and any attempt to modify it will result in a compilation error.
Now, constexpr
is similar to const
, in that it implies a const
. It too, cannot be changed. The difference is, const
can be evaluated at compile-time and run time, depending on how we initialize it.
In this example val
is evaluated at compile-time. When we execute our code, val
always equals 3
. However, in the following example val
is evaluated at run-time because it involves calling a function.