skip to content

In C++, what is the difference between declaring a variable const and declaring it constexpr?

level: juniorimportance: must knowfreq 68%

answer

  1. read-only versus known while compiling
  2. where the initializer comes from
  3. array bounds and template arguments
  4. the integral const exception

basics

~20 s

A const variable cannot be modified after initialization, but its initializer may run at run time. A constexpr variable is also const and must be initialized by a constant expression, so its value can be used in array bounds, template arguments and static_assert.

solid answer

~40 s

`const` is a promise not to modify: `const int kPort = port_from_env();` is fine, and the value is fixed only once that call has run. `constexpr` on a variable demands that the initializer be a constant expression, makes the variable `const`, and guarantees the value is usable in constant expressions: array bounds, template arguments, `case` labels, `static_assert`. If the initializer is not constant, `constexpr` is a compile error, which is the point: it states intent and has the compiler enforce it. One legacy overlap trips people up: a `const` variable of integral or enumeration type initialized with a constant expression is also usable in constant expressions, while a `const double` is not. For a pointer, `constexpr` applies to the pointer object itself, so `constexpr const char* name` is a constant pointer to `const char`.

code

cpp · 13 lines
cpp
#include <cstdlib>
#include <cstdio>
int port_from_env() { const char* p = std::getenv("PORT"); return p ? std::atoi(p) : 8080; }
const int kMaxPacket = 1500;          // const, constant initializer: usable in constant expressions
const int kPort = port_from_env();    // const, but initialized at run time
constexpr int kHeader = 20;           // must be a constant expression
int main() {
    char buf[kMaxPacket - kHeader];   // OK: both are constant expressions
    static_assert(kHeader == 20);
    // static_assert(kPort == 8080);  // error: kPort is not a constant expression
    // constexpr int p = port_from_env();  // error: non-constexpr function
    std::printf("%zu %d\n", sizeof buf, kPort);
}

go deeper

for a junior

Recall that const means not modified after initialization, while constexpr means the value is known while compiling and the compiler checks it.

for a middle

Explain the integral-const exception, why a const double is not a constant expression, and where constexpr applies on a pointer declaration.

for a senior

Make constexpr the default for protocol constants and tables so the compiler enforces them, and keep const for values computed at startup.

for a principal

Set the team rule: constants are constexpr, with const reserved for run-time values, so a reviewer can tell from the keyword when a value is computed.

## Two different promises C++ has two keywords that look alike on a variable declaration and promise different things: - **`const`** says *this object will not be modified after it is initialized*. It says nothing about **when** the initial value is known. `const int kPort = port_from_env();` reads an environment variable at run time and is perfectly valid. - **`constexpr`** says *the value is known while compiling*. The initializer must be a **constant expression**, the variable is implicitly `const`, and the compiler rejects the declaration if the initializer cannot be evaluated at compile time. The practical difference shows up wherever the language requires a constant: an array bound, a non-type template argument, a `case` label, the condition of `static_assert` or `if constexpr`, an `alignas` argument, an enumerator's value. ## A network stack's constants ```cpp const int kMaxPacket = 1500; // const, constant initializer const int kPort = port_from_env(); // const, initialized at run time constexpr int kHeader = 20; // must be a constant expression char buf[kMaxPacket - kHeader]; // OK static_assert(kPort == 8080); // error ``` With Apple clang 21 the last line fails with `static assertion expression is not an integral constant expression` and the note `initializer of 'kPort' is not a constant expression`. Writing `constexpr int p = port_from_env();` fails earlier, at the declaration: `constexpr variable 'p' must be initialized by a constant expression`, because `port_from_env` is not a `constexpr` function. ## The legacy overlap with const integers Before `constexpr` existed (C++11), C++ already let `const` integers serve as constants, and that rule is still in the standard. A variable is **usable in constant expressions** when it is constant-initialized and either declared `constexpr` or of a `const`-qualified **integral or enumeration** type (or a reference). So: | Declaration | Usable in constant expressions? | |---|---| | `const int kMaxPacket = 1500;` | yes: `const` integral, constant initializer | | `const int kPort = port_from_env();` | no: initializer runs at run time | | `const double kGain = 1.5;` | no: not integral or enumeration | | `constexpr double kGain = 1.5;` | yes | The `const double` row surprises people: `static_assert(kGain > 1.0)` fails with `read of non-constexpr variable 'kGain' is not allowed in a constant expression`. Writing `constexpr` removes the special case: it works for any literal type, including floating-point types, `std::array` and your own classes with `constexpr` constructors. ## Details worth knowing 1. **Pointers.** `constexpr` applies to the declared object. `constexpr const char* kName = "eth0";` is a constant pointer to `const char`; the `const` inside is still needed for the pointee. 2. **Static data members.** A `constexpr` static data member is implicitly `inline` (C++17), so `static constexpr int kMtu = 1500;` in a class needs no out-of-class definition. 3. **Linkage.** At namespace scope, a `const` or `constexpr` variable that is not declared `inline` or `extern` has internal linkage, so each translation unit gets its own copy; the material on linkage covers why that matters. 4. **Types.** The type of a `constexpr` variable must be a **literal type**: roughly, scalars, references, arrays of literal types, and classes with a `constexpr` destructor and at least one usable `constexpr` constructor. ## Mistakes interviewers listen for - **Expecting `const` to mean compile time.** `const auto kTimeout = compute_timeout();` is evaluated at run time; nothing about `const` says otherwise. - **`constexpr` on a function parameter.** A parameter's value comes from the caller, so it can never be declared `constexpr`; Apple clang 21 says `function parameter cannot be constexpr`. To force a compile-time argument, make it a template parameter or call a `consteval` function. - **Assuming a `constexpr` variable inside a loop is recomputed.** Its value is fixed while compiling, whatever the loop does. - **Using `#define` for constants.** A macro has no type and no scope; a `constexpr` variable has both, and the material on macros covers the replacement in detail. ## Which to write Use `constexpr` for every value that is meant to be a compile-time constant: protocol numbers, buffer sizes, lookup tables. The compiler then checks that it really is one, and the value is usable everywhere a constant is required. Use `const` for values that are fixed after initialization but computed at run time, such as configuration read at startup.

  • Why can a const int serve as an array bound but a const double cannot serve in static_assert?
    The standard keeps an old rule: a constant-initialized variable is usable in constant expressions if it is `constexpr` or has `const`-qualified integral or enumeration type. A `const int` initialized with a literal qualifies; a `const double` never does, whatever its initializer. Declaring the double `constexpr` makes it usable.
  • Does constexpr on a pointer variable make the pointed-to data const?
    No. `constexpr` applies to the pointer object itself, making it a constant pointer. `constexpr char* p` would point to modifiable `char`, and is valid only if initialized with a constant address, such as that of a static array. To make the pointee read-only too, write `constexpr const char* p`.

  • const and constexpr are synonyms for variables.
  • A const variable's value is always known at compile time.
  • A const double initialized with a literal can be used in static_assert.
  • constexpr on a pointer makes the pointed-to characters const.
  • constexpr variables may be modified once at startup.