CodeBlanks Logo Icon CodeBlanks

constexpr functions

Learn compile-time computation with constexpr functions.

constexpr functions

A constexpr function is an ordinary function that can compute at compile time. Unlike TMP it needs no template; the constexpr keyword is enough. Example: constexpr int square(int x) { return x * x; }.

Called with a constant argument it runs at compile time; with a variable argument it runs at run time. constexpr int s = square(5); produces the constant s = 25 at compile time. This is far more readable than TMP.

Assigning to a constexpr variable

You can assign the result of a constexpr function to a constexpr variable. This variable is a compile-time constant; it can be used as an array size or a template argument. Example: constexpr int area = square(6); creates the constant area = 36.

You can print these constants with std::cout. The compiler resolves square(6) to 36 at compile time; the executable embeds 36.

Practice Write the constexpr square

Write constexpr int square(int x) with body return x * x;. In main define constexpr int area = square(6); and write std::cout << area;.

Starter code

main.cpp
#include <iostream>

// Define the constexpr square function here

int main() {
    // define area and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>

constexpr int square(int x) {
    return x * x;
}

int main() {
    constexpr int area = square(6);
    std::cout << area;
    return 0;
}

Expected output

36

Questions and answers

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

1 What does constexpr int square(int x) enable?

main.cpp
constexpr int square(int x) { return x * x; }
  • Compile-time computation Correct answer
  • Macro only
  • Class membership
  • Run time only

Explanation: constexpr enables compile-time computation with constant arguments.

2 Complete the return statement

Question
constexpr int square(int x) { return x * ____; }
Answer
constexpr int square(int x) { return x * x; }

Explanation: Write return x * x; the multiplier for square is x.

3 Match each call to its result

Term Meaning
square(2) returns 4
square(5) returns 25
square(6) returns 36
square(10) returns 100

All lessons in Expert