CodeBlanks Logo Icon CodeBlanks

constexpr

Learn to define compile-time constants with constexpr.

constexpr

constexpr indicates that a variable's value can be computed at compile time. When you write constexpr int width = 800;, the compiler computes 800 during compilation and embeds it in the executable.

The difference between const and constexpr: const only guarantees immutability (the value may be determined at runtime); constexpr guarantees both immutability and compile-time evaluability.

constexpr is used where constant expressions are required (array sizes, template parameters). The compiler can optimize better.

Using constexpr

A variable declared with constexpr must have a value the compiler can compute. So the right-hand side must be a constant expression: constexpr int area = 20 * 30; is valid because 20 * 30 is computed at compile time.

But constexpr int x = readValue(); is invalid because readValue() is called at runtime. In this case use const.

constexpr functions can also be defined: when called in a constant expression context, they run at compile time. This is common in modern C++ for performance.

Practice Define sizes with constexpr

Above main (in the global scope), declare two constexpr int values: width with value 800 and height with value 600. Inside main, add two std::cout lines: the first prints width, the second height; end each line with std::endl.

Starter code

main.cpp
#include <iostream>

// Define two sizes with constexpr

int main() {
    // Print with std::cout
    return 0;
}

Sample solution

main.cpp
#include <iostream>

// Define two sizes with constexpr
constexpr int width = 800;
constexpr int height = 600;

int main() {
    // Print with std::cout
    std::cout << width << std::endl;
    std::cout << height << std::endl;
    return 0;
}

Expected output

800
600

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between constexpr and const?

  • constexpr is evaluated at compile time Correct answer
  • const is faster
  • constexpr is only for double
  • const is only used in classes

Explanation: const may hold a runtime value.

2 Match constexpr concepts

Term Meaning
constexpr Compile-time constant
20 * 30 Constant expression
readValue() Runtime
array size Requires constexpr

3 Compile-time constant

Question
____ int width = 800;
Answer
constexpr int width = 800;

Explanation: constexpr int width is a compile-time constant.

All lessons in Beginner