constexpr
In this lesson, we'll study constexpr.
Constant Expressions
You can define, with the keyword constexpr
, an expression that can be evaluated at compile-time. constexpr
can be used for variables, functions, and user-defined types. An expression that is evaluated at compile-time has a lot of advantages.
A constant expression
- can be evaluated at compile-time.
- gives the compiler deep insight into the code.
- is implicitly thread-safe.
constexpr
- Variables and Objects
If you declare a variable as constexpr
, the compiler will evaluate them at compile-time. This holds not only true for built-in types but also for instantiations of user-defined types. There are a few serious restrictions for objects in order to evaluate them at compile-time.
To make life easier for us, we will call the C types like bool
, char
, int
, and double
primitive data types. We will call the remaining data types as user-defined data types. These are for example, std::string
, types from the C++ library and non-primitive data types. Non-primitive data types typically hold primitive data types.
Variables
By using the keyword constexpr
, the variable becomes a constant expression.
constexpr double pi= 3.14;
Therefore, we can use the variable in contexts that require a constant ...