← Back to C++ Course | Chapter 16: Modern C++ | Lesson 6 of 9

C++ constexpr

What is constexpr?

constexpr marks an expression or function as evaluable at compile time when given compile-time-constant inputs, letting the compiler compute the result once during compilation instead of recalculating it every time the program runs.

Example: What is constexpr?

cpp
#include <iostream>

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

int main() {
	constexpr int result = square(5);
	std::cout << result << std::endl;
	return 0;
}

constexpr Functions

A constexpr function is written like a normal function, but when every argument passed to it is itself a compile-time constant, the compiler evaluates the entire function body during compilation and substitutes the result directly -- if any argument isn't a compile-time constant, it simply falls back to running as a normal function at runtime.

Example: constexpr Functions

cpp
#include <iostream>

constexpr int factorial(int n) {
	return (n <= 1) ? 1 : n * factorial(n - 1);
}

int main() {
	std::cout << factorial(5) << std::endl;
	return 0;
}

constexpr vs. const

const only promises that a variable's value won't change after initialization -- that initialization can still happen at runtime, based on something like user input. constexpr goes further, requiring the value to be fully computable at compile time, which is a stronger and more restrictive guarantee.

Example: constexpr vs. const

cpp
#include <iostream>

int main() {
	int runtimeInput = 5;
	const int a = runtimeInput;
	constexpr int b = 10;
	std::cout << a << " " << b << std::endl;
	return 0;
}

constexpr Constructors

A constexpr constructor allows an entire class object -- not just a single value -- to be fully constructed during compilation, provided every member is itself initialized with compile-time-constant expressions. This lets you build whole lookup tables or configuration objects with zero runtime cost.

Example: constexpr Constructors

cpp
#include <iostream>

class Point {
public:
	int x, y;
	constexpr Point(int px, int py) : x(px), y(py) {}
};

int main() {
	constexpr Point p(3, 4);
	std::cout << p.x << "," << p.y << std::endl;
	return 0;
}

Performance Gains

Moving computation from runtime to compile time means the CPU never spends cycles on it while the program is actually running -- for math that depends only on constants (like a fixed-size buffer length or a mathematical table), constexpr effectively makes that computation free at runtime.

Example: Performance Gains

cpp
#include <iostream>

constexpr int bufferSize = 10 * 10;

int main() {
	int buffer[bufferSize];
	std::cout << bufferSize << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.