Is a blank return statement at the end of a function whos return type is void necessary?(返回类型为 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 的函数末尾是否需要空白返回语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回类型为 void 的函数末尾是否需要空白返回语句?


- Qt计时器使用方法详解 2023-05-30
- Easyx实现扫雷游戏 2023-02-06
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- ubuntu下C/C++获取剩余内存 2023-09-18
- C语言qsort()函数的使用方法详解 2023-04-26
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- C语言详解float类型在内存中的存储方式 2023-03-27
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- C++ 数据结构超详细讲解顺序表 2023-03-25
- C语言手把手带你掌握带头双向循环链表 2023-04-03