Home Item 15 - constexpr function (English)
Post
Cancel

Item 15 - constexpr function (English)

Constant Expression Functions

In C++11, constexpr functions were restricted to using very limited syntax. In C++14, support for constexpr functions has been expanded, including allowing the use of if statements and defining local variables within functions.

The main limitations include

  1. Only allowing a single return statement. In other words, a function can have only one return statement.
  2. Not allowing the declaration of local variables inside the function body.
  3. Not allowing the use of loops, recursion, or other complex control structures. These limitations restrict constexpr functions in C++11 to very simple calculations and operations and prevent them from handling complex logic and algorithms.

Let’s see some code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

// Define a constexpr function to calculate the absolute value of a given number
constexpr int abs(int x) {
    if (x < 0) {
        return -x;
    } else {
        return x;
    }
}

int main() {
    constexpr int num = -10;
    constexpr int result = abs(num); // Calculate the absolute value at compile time
    std::cout << "Absolute value: " << result << std::endl;
    return 0;
}


In the above example, constexpr function uses if statement and two return statements, which were not allowed in C++11!!! It would result in errors.

Desktop View

Changing the language version to C++14 or above will yield the correct result.

Desktop View

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍