The body of constexpr function not a return-statement

msc picture msc · Jul 14, 2017 · Viewed 10.2k times · Source

In the following program, I have added an explicit return statement in func(), but the compiler gives me the following error:

m.cpp: In function ‘constexpr int func(int)’:
m.cpp:11:1: error: body of constexpr function ‘constexpr int func(int)’ not a return-statement
 }

This is the code:

#include <iostream>
using namespace std;

constexpr int func (int x);

constexpr int func (int x) 
{
    if (x<0)                
        x = -x;
    return x; // An explicit return statement 
}

int main() 
{
    int ret = func(10);
    cout<<ret<<endl;
    return 0;
}

I have compiled program in a g++ compiler using the following command.

g++ -std=c++11 m.cpp

I have added return statement in function, then Why I got above error?

Answer

Thomas picture Thomas · Jul 14, 2017

Prior to C++14, the body of a constexpr function must consist solely of a return statement: it cannot have any other statements inside it. This works in C++11 :

constexpr int func (int x) 
{
  return x < 0 ? -x : x;
}

In C++14 and up, what you wrote is legal, as are most other statements.

Source.