Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 171 ยท Variables and Types

Constants: const, constexpr and consteval

Learn C++ constants - const for values that never change, constexpr for compile-time values and functions, consteval and constinit, and why #define constants are a bad idea.

Many values in a program should never change once they are set: the number of days in a week, a tax rate loaded at startup, the maximum size of a buffer, a user's ID after login. Marking them as constants lets the compiler enforce that promise. An accidental assignment becomes a compile error instead of a bug you hunt down at 2 a.m.

C++ has more ways to say "constant" than most languages, because it distinguishes two different ideas: a value that can't be modified (const), and a value that is known at compile time (constexpr). In this lesson you'll learn both, plus their newer relatives consteval and constinit, and why the old #define approach should stay in the past.

const: this value will not change

Put const before (or after) the type, and the variable becomes read-only. It must be initialized, because you can never assign to it later:

C++ A const variable cannot be assigned (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Press Run and the compiler refuses: error: assignment of read-only variable 'days_per_week'. Delete the last line and it runs. That is the whole point: the mistake is caught before the program exists.

A const variable's value doesn't have to be known at compile time. It can come from user input, a calculation or a function call. It is fixed from the moment it is initialized:

C++ const values from run time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

You can call any member function on a const object that doesn't modify it (like size()), but not one that does (name += "!" won't compile). This is the start of const correctness, a habit that runs through all good C++ code: make everything const that doesn't need to change. It documents intent, prevents bugs, and makes code easier to reason about, because a reader knows a const value is the same on line 50 as on line 5.

const also appears with references (const std::string& parameters, which you'll meet in Parameters), with pointers (const with Pointers and References), and with member functions (const Member Functions).

constexpr: known at compile time

A constexpr variable is const and its value must be computed by the compiler. The initializer has to be a constant expression: literals, other compile-time constants, and calls to constexpr functions with compile-time arguments.

C++
constexpr int seconds_per_day = 24 * 60 * 60;   // computed by the compiler
constexpr double pi_half = 3.141592653589793 / 2;

int n = 5;
constexpr int doubled = n * 2;   // error: n is not a constant expression

The last line fails with the value of 'n' is not usable in a constant expression. A plain int variable could change before this line runs, so the compiler can't know its value. (A const int n = 5; initialized with a literal would work, a special rule for integral const variables, but constexpr says what you mean.)

Why would you want compile-time values? Because some places in C++ require them:

  • array sizes: std::array<int, size> and C arrays
  • template arguments, like that size
  • case labels in a switch
  • static_assert conditions
  • if constexpr conditions (see Compile-Time Programming)

And because work done at compile time costs nothing at run time.

C++ constexpr values where the compiler needs them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Change board_size to 9 and run again: the static_assert stops compilation with your message. Assertions like this turn assumptions into checks that can never be forgotten. You'll meet std::array properly later.

constexpr functions (a preview)

A function marked constexpr can run at compile time, when its arguments are compile-time constants and the result is needed in a constant expression. With run-time arguments, it runs as a normal function. One definition, both uses:

C++ One function, compile time and run time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Since C++14, constexpr functions can contain loops, local variables and if statements, and each standard since has allowed more (C++20 added std::vector and std::string inside them, as long as the memory is freed before compile-time evaluation ends). What they can't do at compile time is anything with side effects outside the computation, like I/O. The full story, including compile-time lookup tables, is in Compile-Time Programming: constexpr and consteval.

consteval and constinit (C++20)

Two newer keywords cover the remaining cases. You won't need them often, but you will see them in modern code.

consteval makes an immediate function: it must run at compile time. Calling it with a run-time value is an error, which is useful when a run-time call would be a mistake (for example, validating a format string or hashing a fixed name).

C++ consteval must run at compile time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Uncomment the last two lines and the compiler reports call to consteval function 'kilobytes(pages)' is not a constant expression, followed by a note that pages is not const. With constexpr instead of consteval, the same call would compile and simply run at run time.

constinit applies to variables with static or thread storage duration (globals, static locals; see Scope, Lifetime and Storage Duration). It guarantees the variable is initialized at compile time, avoiding the "static initialization order fiasco" between source files, but it does not make the variable constant:

C++
constinit int request_count = 0;   // initialized at compile time...

void handle_request() {
    ++request_count;               // ...and still modifiable
}
Keyword Value fixed? Must be known at compile time? Applies to
const yes no variables, references, pointers, member functions
constexpr yes yes (variables); "can be" (functions) variables, functions
consteval n/a always evaluated at compile time functions
constinit no initializer only static/thread-storage variables

Rule of thumb: constexpr for every constant whose value you know when writing the code, const for values computed at run time. Reach for consteval and constinit only when you need their specific guarantees.

Magic numbers

A magic number is a literal in the middle of code whose meaning isn't obvious:

C++
if (password.size() < 12) { ... }
double price = net * 1.21;
sleep_for(86'400s);

Is 12 a policy? Is 1.21 a tax rate, and which country's? Named constants answer those questions and give you one place to change the value:

C++
constexpr std::size_t min_password_length = 12;
constexpr double vat_multiplier = 1.21;        // 21% Dutch VAT
constexpr auto one_day = std::chrono::days{1};

if (password.size() < min_password_length) { ... }
double price = net * vat_multiplier;

Not every literal is magic. 0, 1, 2 in i + 1 or x / 2, and 100 in a percentage formula are usually clear in context. Name a value when a reader would ask "why this number?", or when it appears in more than one place.

Why not #define?

Older C and C++ code defines constants with the preprocessor:

C++
#define MAX_PLAYERS 4
#define PI 3.14159
#define SQUARE(x) x * x

The preprocessor runs before the compiler and does plain text replacement. That causes real problems:

  • No type. MAX_PLAYERS is just the characters 4. The compiler never sees a name, so error messages and debuggers show 4, not MAX_PLAYERS.
  • No scope. A macro is visible from its definition to the end of every file that includes it, ignoring namespaces, classes and functions. A macro named max or ERROR in one header can break completely unrelated code (Windows' windows.h famously defines min and max macros).
  • Surprising expansion. Text substitution ignores operator precedence:
C++ The macro trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The macro versions print 5 and 140 instead of 9 and 240. Adding parentheses everywhere fixes these two cases, but not the scope and type problems. constexpr variables and functions give you the same zero run-time cost with none of the drawbacks.

Macros still have legitimate jobs: include guards, conditional compilation (#ifdef _WIN32), and a few debugging tools like assert. Constants aren't one of them.

Constants in headers

When a constant is shared between several .cpp files, put it in a header as an inline constexpr variable (C++17):

C++
// config.h
#pragma once

inline constexpr int max_players = 4;
inline constexpr double gravity = 9.81;

At namespace scope, constexpr variables are already private to each file (they have internal linkage), so even without inline the code would compile. Adding inline makes all files share a single object, which avoids duplicate copies and keeps addresses consistent. Header Files and Multiple Source Files explains the details.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which declaration compiles?

    A const variable may be initialized from a run-time value. constexpr requires a constant expression, and both const and constexpr variables must be initialized.
  2. 2. What does SQUARE(2 + 3) give with #define SQUARE(x) x * x?

    The text becomes 2 + 3 * 2 + 3, and multiplication binds tighter, giving 2 + 6 + 3 = 11. A constexpr function would give 25.
  3. 3. A constexpr function is called with a value read from std::cin. What happens?

    constexpr functions can run at compile time but don't have to. With a run-time argument they simply run at run time. Only consteval functions must run at compile time.
  4. 4. Which is true about constinit int counter = 0;?

    constinit guarantees compile-time initialization of a static-storage variable. It does not imply const.
  5. 5. Where can you use a const int read from user input?

    Its value is only known at run time, so it can't be used where a constant expression is required. It works anywhere a normal read-only value does.

Summary

  • const makes a variable read-only after initialization; its value may come from run time. Make everything const that doesn't need to change.
  • constexpr variables are const and computed at compile time, so they work for array sizes, template arguments, case labels and static_assert.
  • constexpr functions can run at compile time with constant arguments and at run time otherwise; consteval functions must run at compile time.
  • constinit guarantees compile-time initialization of globals and statics without making them constant.
  • Replace magic numbers with well-named constexpr constants.
  • Avoid #define for constants: macros have no type, no scope and expand as raw text. Use inline constexpr in headers for shared constants.

Next: Type Conversions and Casts, where you'll learn what C++ converts automatically, what it refuses to, and how to convert on purpose with static_cast.