C++ constexpr Keyword

The constexpr keyword in C++ is used to define variables, functions, and constructors that can be evaluated at compile-time. It ensures that certain computations are performed during compilation, improving performance and guaranteeing constant expressions where required.

The constexpr keyword was introduced in C++11 and has been enhanced in subsequent standards (C++14, C++17, and C++20). It can be used for variables, functions, constructors, and even member functions of a class.


Syntax

</>
Copy
// Constant variable
constexpr data_type variable_name = value;

// Constant expression function
constexpr return_type function_name(parameters) {
    // Function body
}

// Constant expression constructor
class ClassName {
public:
    constexpr ClassName(parameters) {
        // Constructor body
    }
};
constexpr
The keyword used to declare compile-time constants, functions, or constructors.
data_type
The type of the variable or the return type of the function.
variable_name
The name of the constant variable.
parameters
The input parameters required for the function or constructor.

Examples

Example 1: Declaring a constexpr Variable

This example demonstrates how to declare and use a constexpr variable.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    constexpr int MAX_LIMIT = 100; // Compile-time constant
    cout << "Maximum Limit: " << MAX_LIMIT << endl;

    // Uncommenting the following line will cause a compilation error
    // MAX_LIMIT = 200;

    return 0;
}

Output:

Maximum Limit: 100

Explanation:

  1. The MAX_LIMIT variable is declared as constexpr, ensuring it is evaluated and initialized at compile-time.
  2. Attempting to modify MAX_LIMIT will result in a compilation error.

Example 2: constexpr Function

This example demonstrates a constexpr function to compute the square of a number at compile-time.

</>
Copy
#include <iostream>
using namespace std;

// Define a constexpr function
constexpr int square(int x) {
    return x * x;
}

int main() {
    constexpr int result = square(5); // Compile-time evaluation
    cout << "Square of 5: " << result << endl;

    // It can also be used in runtime expressions
    int runtime_result = square(6);
    cout << "Square of 6: " << runtime_result << endl;

    return 0;
}

Output:

Square of 5: 25
Square of 6: 36

Explanation:

  1. The function square is declared as constexpr, ensuring it can be evaluated at compile-time.
  2. The variable result is initialized at compile-time using square(5).
  3. The function can also be used in runtime contexts, such as initializing runtime_result with square(6).

Example 3: constexpr Constructor

This example demonstrates a constexpr constructor to initialize a class object at compile-time.

</>
Copy
#include <iostream>
using namespace std;

class Rectangle {
private:
    int width, height;

public:
    // Define a constexpr constructor
    constexpr Rectangle(int w, int h) : width(w), height(h) {}

    constexpr int area() const {
        return width * height;
    }
};

int main() {
    constexpr Rectangle rect(4, 5); // Compile-time object
    constexpr int area = rect.area();
    cout << "Area: " << area << endl;

    return 0;
}

Output:

Area: 20

Explanation:

  1. The Rectangle class defines a constexpr constructor and a constexpr member function.
  2. An object rect is created at compile-time using the constexpr constructor.
  3. The area of the rectangle is computed during compilation and stored in the area variable.

Key Points about constexpr Keyword

  1. The constexpr keyword ensures that variables, functions, or constructors can be evaluated at compile-time.
  2. It improves performance by moving computations to compile-time instead of runtime.
  3. constexpr functions can also be used in runtime contexts, but their compile-time evaluation is preferred when possible.
  4. Starting from C++14, constexpr functions can contain multiple statements, including loops and conditionals.
  5. Use constexpr for compile-time constants, mathematical functions, and class initializations to make your code efficient and expressive.