constexpr in C++ 11 and C++ 14

In the previous post, we were talking about the constexpr keyword in modern C++. It was added to the C++ 11 standard, but in C++ 14, it got a very nice addition. In particular, you can do more in constexpr functions now.

Consider the following program that wants to pre-compute a factorial of 5.

#include <iostream>

int factorial(int n) {
    int r = 1;
    do r *= n; while (--n);
    return r;
}

int main() {
    auto f5 = factorial(5);
    std::cout << f5 << std::endl;
}

Obviously, f5 is a constant, and even more, it is a constant expression. Although, you cannot declare it as constexpr in C++ 11.

The following updated program is an example of how you would do it:

#include <iostream>

constexpr int factorial(int n) {
    int r = 1;
    do r *= n; while (--n);
    return r;
}

int main() {
    constexpr auto f5 = factorial(5);
    std::cout << f5 << std::endl;
}

If you compile the program against the C++ 11 standard, you get an error:

$ g++ -std=c++11 test.cpp 
test.cpp:4:9: warning: variable declaration in a constexpr function is a C++14 extension [-Wc++14-extensions]
     int r = 1;
         ^
test.cpp:5:5: error: statement not allowed in constexpr function
     do r *= n; while (--n);
     ^
 1 warning and 1 error generated.

Actually, the error message gives a solution. Switch to C++ 14:

$ g++ -std=c++14 test.cpp 
$ ./a.out 
120

Leave a Reply

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

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code