Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The body of constexpr function not a return-statement

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?

like image 581
msc Avatar asked Jul 14 '17 07:07

msc


People also ask

Can a function return constexpr?

Unlike const , constexpr can also be applied to functions and class constructors. constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time.

What is a constexpr function?

A constexpr function is a function that can be invoked within a constant expression. A constexpr function must satisfy the following conditions: It is not virtual. Its return type is a literal type. Each of its parameters must be of a literal type.

Are constexpr functions static?

The constexpr function is executed in a context that is evaluated at compile time. This can be a static_assert expression, such as with the type-traits library or the initialization of a C-array.

Can a member function be constexpr?

const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.


2 Answers

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.

like image 174
Thomas Avatar answered Oct 23 '22 18:10

Thomas


C++11's constexpr functions are more restrictive than that.

From cppreference:

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
  • exactly one return statement.

So you can say this instead:

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

static_assert(func(42) == 42, "");
static_assert(func(-42) == 42, "");

int main() {}

Note that this restriction was lifted in C++14.

like image 33
mpark Avatar answered Oct 23 '22 17:10

mpark