...

/

Constant Expressions: constexpr

Constant Expressions: constexpr

In this lesson, we will see how constexpr is used in modern C++.

Constant expressions #

With constexpr, we can define 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
  • can be constructed in the read-only memory (ROM-able)

constexpr - variables and objects #

If we declare a variable as constexpr, the compiler will evaluate it at compile time. This holds true not only for built-in types but also for instantiations of user-defined types. There are a few serious restrictions for objects in order ...