• Home
  • 6.14 constexpr Functions

6.14 constexpr Functions

View Categories

6.14 constexpr Functions

1 min read

Table of Contents

A constexpr function is a function that can be evaluated at compile time when it is called with arguments that permit constant evaluation. The constexpr specifier indicates that the function is intended to be usable in constant expressions.

A constexpr function can also be called at runtime when its arguments or context do not permit compile-time evaluation. This allows the same function to be used in both compile-time and runtime contexts.

Source Code #

#include <iostream>

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

int main()
{
    constexpr int result = square(5);

    std::cout << "Square: " << result << '\n';

    return 0;
}

Output #

Square: 25

Explanation #

  • The constexpr specifier declares square() as a function that can participate in constant evaluation.
  • square() accepts an int parameter and returns an int.
  • return number * number; calculates the square of the supplied value.
  • constexpr int result = square(5); requires square(5) to produce a constant expression because result is declared constexpr.
  • The compiler can evaluate square(5) during compilation.
  • A constexpr function is not restricted to compile-time execution; it can also be called at runtime when compile-time evaluation is not possible or required.
  • The rules governing what a constexpr function may contain have expanded across successive C++ standards.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *