notaorb
notaorb

Reputation: 2180

constexpr with conditional statement error, using Stroustrup example

Stroustrup C++ 4th Ed. Page 311 describes constexpr fac for factorial, which includes a conditional statement. Then on Page 312, describes constexpr bad2 with a conditional statement and a comment that it results in an error. He also states on Page 312 that "A constexpr function allows recursion and conditional expressions."

What is the difference between the two functions and the conditional statement that result in the error?

#include <iostream>
using namespace std;

constexpr int fac(int n)
{
    return (n > 1) ? n*fac(n-1) : 1;
}

constexpr int bad2(int a)
{
    if (a>=0) return a; else return -a; // error: if-statement in constexpr function
}

int main(int argc, char *argv[])
{
    constexpr int c = 3;
    cout << fac(c) << endl;
    cout << bad2(c) << endl;

    return 0;
}

Compilation and results:

g++ -pedantic -Wall test135.cc && ./a.out
6
3

bad2 indeed results in an error in C++11 mode.

g++ -pedantic -Wall -std=c++11 test135.cc && ./a.out
test135.cc: In function ‘constexpr int bad2(int)’:
test135.cc:12:1: error: body of ‘constexpr’ function ‘constexpr int bad2(int)’ not a return-statement
 }

Upvotes: 2

Views: 122

Answers (1)

songyuanyao
songyuanyao

Reputation: 172934

Before C++14, if statement can't be used in constexpr functions, and it could have exactly one return statement.

(until C++14)

  • the function body must be either deleted or defaulted or contain only the following:
    • null statements (plain semicolons)
    • static_assert declarations
    • typedef declarations and alias declarations that do not define classes or enumerations
    • using declarations
    • using directives
    • if the function is not a constructor, exactly one return statement

So until C++14 it was general to use conditional operator (instead of if) and recursion (instead of loop), and constrain in single return statement for constexpr functions.

Since C++14 using if statement, multiple return statements and loops are allowed.

Upvotes: 2

Related Questions