Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 7 of 10
Constants - const, constexpr & enum class
`const` is a runtime-or-compile-time immutability marker. `constexpr` (C++11) means **must be evaluated at compile time** - enabling constants in array sizes, template arguments, and `if constexpr`. `enum class` (C++11) is scoped and strongly typed - the only correct way to define enumerations in modern C++.
const vs constexpr vs enum class - Modern Constant Patterns
#include <iostream>
#include <array>
// ── const - immutable at runtime ─────────────────────────────
const double TAX_RATE = 0.18; // file-scope const (internal linkage in C++)
// ── constexpr - guaranteed compile-time ──────────────────────
constexpr int MAX_USERS = 1024; // can be used as array size
constexpr double PI = 3.14159265358979;
// constexpr function - evaluated at compile time if args are constexpr
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
constexpr int FACT_5 = factorial(5); // computed at compile time: 120
// ── enum class - scoped, strongly-typed (C++11) ───────────────
enum class Direction { North, South, East, West };
enum class Colour { Red, Green, Blue };
// Can assign explicit values
enum class HttpStatus : int {
OK = 200,
NotFound = 404,
ServerError = 500,
};
// ── old-style enum (don't use in new code) ────────────────────
// enum OldDirection { North, South, East, West }; // North leaks to global scope!
std::string direction_name(Direction d) {
switch (d) {
case Direction::North: return "North";
case Direction::South: return "South";
case Direction::East: return "East";
case Direction::West: return "West";
}
return "Unknown";
}
int main() {
// constexpr array size
std::array<int, MAX_USERS> ids{}; // stack array of 1024 ints
ids[0] = 1;
std::cout << "PI = " << PI << "
";
std::cout << "5! = " << FACT_5 << "
"; // 120
std::cout << "TAX = " << TAX_RATE << "
"; // 0.18
Direction d = Direction::North;
std::cout << direction_name(d) << "
";
// Strongly-typed: cannot mix enum classes
// if (d == Colour::Red) { } ← compile error: different enum types
// Access underlying value explicitly
int code = static_cast<int>(HttpStatus::NotFound);
std::cout << "404 code = " << code << "
";
// ── if constexpr (C++17) - compile-time branching ─────────
constexpr bool IS_DEBUG = false;
if constexpr (IS_DEBUG) {
std::cout << "DEBUG MODE
"; // compiled out in release
} else {
std::cout << "RELEASE MODE
";
}
return 0;
}Common Mistakes
- `const` without `constexpr` may not be a compile-time constant - `const int n = get_n();` is a runtime const. You cannot use it as a template argument or array size. Only `constexpr` guarantees compile-time evaluation.
- Old `enum` pollutes the enclosing namespace - `enum Direction { North, South }` - `North` and `South` are now in the enclosing scope. If two enums in the same scope have a member named the same, you get a conflict. Always use `enum class`.
- Casting `enum class` to int for switch - `switch (static_cast<int>(myEnum))` defeats type safety. Use `switch (myEnum)` directly and match `case Direction::North:` style patterns.
Tip
Tip
Practice Constants const constexpr enum class in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Compile-Time Immutability, Metaprogramming Guarantees, and Type-Safe enum class
Practice Task
Note
Practice Task - (1) Write a working example of Constants const constexpr enum class from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Constants const constexpr enum class is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- `const` is a runtime-or-compile-time immutability marker.
- `const` without `constexpr` may not be a compile-time constant - `const int n = get_n();` is a runtime const. You cannot use it as a template argument or array size. Only `constexpr` guarantees compile-time evaluation.
- Old `enum` pollutes the enclosing namespace - `enum Direction { North, South }` - `North` and `South` are now in the enclosing scope. If two enums in the same scope have a member named the same, you get a conflict. Always use `enum class`.
- Casting `enum class` to int for switch - `switch (static_cast<int>(myEnum))` defeats type safety. Use `switch (myEnum)` directly and match `case Direction::North:` style patterns.
Finished this lesson?