c语言expr,C语言 constexpr函数的主体不是return语句

在下面的程序中,我在func()中添加了一个显式的return语句,但编译器给出了以下错误:

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

}

这是代码:

#include

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<

return 0;

}

我使用以下命令在g编译器中编译程序.

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

我在函数中添加了return语句,然后为什么我出错了?

C 11的constexpr功能比这更具限制性.

从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.

所以你可以这样说:

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

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

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

int main() {}

请注意,此限制已在C 14中解除.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值