Skip to main content

constexpr and enum class

intermediate25 min readLesson 103 of 204

Compile-time computation with static_assert, and scoped enums that refuse accidental int conversions.

Two features move work from runtime to compile time โ€” and make intent visible to both the compiler and the reader.

constexpr marks an expression or function as computable at compile time when given constant arguments:

constexpr int max_users = 1000;              // a true constant
constexpr int square(int x) { return x * x; }
static_assert(square(7) == 49);              // proven at compile time

enum class is a scoped, strongly-typed enum: enumerators live inside the enum's name, do not leak, do not implicitly convert to int, and the underlying type is your choice:

enum class Status { Ok, NotFound, Error };

Status s = Status::Ok;
// int x = s;            // error: no implicit conversion โ€” the whole point
if (s == Status::Ok) { }  // comparisons are type-checked

The classic bug enum class eliminates: two unrelated unscoped enums (or an enum and an int) silently comparing equal. Prefer it for every new enumeration; pass it by value; switch over it exhaustively โ€” most compilers warn when a switch misses an enumerator.

Now practice

optional and enum practiceA null-safe divide and a weighted enum with an exhaustive switch.2 challenges ยท ยท ~25 min