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

C++ constexpr

constexpr tells C++ a value or function can be worked out before the program even runs, like doing homework in advance. It makes programs faster and values fixed.
Syntax
cpp
constexpr data_type variable_name = compile_time_value;

constexpr return_type function_name(parameters) {
  return expression;
}

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 std::cout and std::cin
#include <iostream>

constexpr int square(int x) {
	// Send x * x back to the caller
	return x * x;
}

// Program execution starts in main()
int main() {
	constexpr int result = square(5);
	// Print to the console with cout
	std::cout << result << std::endl;
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

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

// Program execution starts in main()
int main() {
	// Print to the console with cout
	std::cout << factorial(5) << std::endl;
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

// Program execution starts in main()
int main() {
	// Declare runtimeInput and set it to 5
	int runtimeInput = 5;
	// Declare a and set it to runtimeInput
	const int a = runtimeInput;
	constexpr int b = 10;
	// Print to the console with cout
	std::cout << a << " " << b << std::endl;
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

// Define the type Point
class Point {
// Members below can be accessed from outside the class
public:
	int x, y;
	constexpr Point(int px, int py) : x(px), y(py) {}
};

// Program execution starts in main()
int main() {
	constexpr Point p(3, 4);
	// Print to the console with cout
	std::cout << p.x << "," << p.y << std::endl;
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

constexpr int bufferSize = 10 * 10;

// Program execution starts in main()
int main() {
	int buffer[bufferSize];
	// Print to the console with cout
	std::cout << bufferSize << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using a non-constant value in a constexpr variable, which does not compile.
  2. Confusing const (runtime constant) with constexpr (compile-time constant).
  3. Calling a non-constexpr function inside a constexpr initializer.

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.