Home > On-Demand Archives > Talks >

Compile-Time Programming in C++ Using Constexpr

Ben Saks - Watch Now - EOC 2023 - Duration: 42:47

Compile-Time Programming in C++ Using Constexpr
Ben Saks

Prerequisite: Solid knowledge of the C, as well as the fundamentals of C++ classes, constructors, and the const qualifier.

C++’s constexpr qualifier is a powerful tool for writing “constant expressions” — that is, expressions that can be computed at compile time. These constant expressions have several advantages over non-constant expressions, particularly for embedded systems. Objects with values that are constant expressions can be placed in ROM (read-only memory), and can be used as array dimensions, case labels, and enumerator initializers. Moreover, code that uses constant expressions is generally smaller and faster than similar code that uses non-constant expressions.

In this session, we’ll look at how you can use the constexpr qualifier to write functions that yield constant expressions. We’ll examine the differences between const and constexpr objects and see why const objects don’t necessarily qualify as constant expressions. We’ll also discuss the related C++20 keywords consteval and constinit and see how they fit into the picture.

This session covers:

  • A review of the fundamentals of const
  • constexpr functions
  • constexpr objects
  • consteval functions
  • constinit objects
italicssurround text with
boldsurround text with
**two asterisks**
or just a bare URL
surround text with
strikethroughsurround text with
~~two tilde characters~~
prefix with

Score: 1 | 1 year ago | 1 reply

Thanks Ben for the talk. I think I have seen that constexpr is coming to C23 for variables. Could you explain a bit here how it compare to current const keyword in C and to constexpr in C++11 and later ?

Score: 1 | 1 year ago | no reply

Hi Nathan3, glad you enjoyed the talk.
Compiler support for the C23 version of constexpr seems to be fairly new, but it appears that the C23 version of constexpr will be a strict subset of the constexpr features available in C++. C23 will permit some kinds of constexpr objects, but not constexpr functions. As such, some existing C++ code will be valid C23 code, making life easier for those who need their code to compile as either C or C++. We'll also be able to use constexpr objects where today we would use macros; that will be nice because (unlike evaluating a macro), evaluating a constexpr object can't produce side effects.
Unlike const objects, constexpr objects will be considered constant expressions in both C and C++. As such, you'll be able to use constexpr objects in contexts that require constant expressions, such as enum definitions:
int const cx1 = 10;
enum { e1 = cx1 }; // valid in C++, but not in C

 constexpr int cx2 = 20;
 enum { e2 = cx2 };    // valid in C++ and C23

 Hope that helps - let me know if you have additional questions.