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
}