返回类型为 void 的函数末尾是否需要空白返回语句? [英] Is a blank return statement at the end of a function whos return type is void necessary?

查看:56
本文介绍了返回类型为 void 的函数末尾是否需要空白返回语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 SO 的大多数问题都涉及非 void 返回类型,但我们正在为此展开一场激烈的战争,并想了解社区的想法.

Most of the questions on SO refer to non-void return types, but we are having a flame war at work about this and wanted to find out what the community thought.

void DoSomething()
{
   return; // Is this needed?
}

来自 this 讨论,看起来未定义行为的问题涉及非 void 返回类型的函数.void 返回类型是否具有相同的未定义行为,还是仅在非 void 返回函数中?

From this discussion, it looks like the issue of having an undefined behavior deals with functions of non-void return types. Do void return types have this same undefined behavior, or is it only in the non-void returning function?

我担心的是,这最终会成为一种糟糕的编码风格,没有任何理由可以证明这一点.但是,如果它也是 void 返回函数的未定义行为,那么我可以看到需要将其添加到编码标准中.如果 C 与 C++ 的答案不同,那也没关系.

My concern is that this will just end up as a terrible coding style that isn’t justified by anything. However if it’s also an undefined behavior for void return functions, then I can see the need for adding it to the coding standard. If the answer is different for C vs C++ this is ok too.

§ 6.6.3 返回语句

§ 6.6.3 The return statement

2 没有表达式的 return 语句只能用于不返回值的函数,即具有返回 void 类型、构造函数 (12.1) 或析构函数 (12.4).

2 A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type of void, a contrsuctor(12.1), or a destructor(12.4).

§ 6.6.3/2

从函数的末尾流出的是相当于没有价值的回报;这会导致未定义的行为在一个值返回函数.

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

推荐答案

No;这不是必需的.

如果你想提前返回,你只需要写 return; 并跳过函数的其余部分.

You only need to write return; if you want to return early and skip the rest of the function.

这篇关于返回类型为 void 的函数末尾是否需要空白返回语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆