Skip to content

Commit 1eeb265

Browse files
author
Arendelle
committed
update functions.md: noreturn
1 parent 1fe985e commit 1eeb265

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

docs/functions.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,19 @@ void compute()
3838
> {{ icon.warn }} 对于返回类型不为 `void` 的函数,必须写 `return` 语句,如果漏写,会出现可怕的未定义行为 (undefined behaviour)。编译器不一定会报错,而是到运行时才出现崩溃等现象。建议 GCC 用户开启 `-Werror=return-type` 让编译器在编译时就检测此类错误,MSVC 则是开启 `/we4716`。更多未定义行为可以看我们的[未定义行为列表](undef.md)章节。
3939
> {{ icon.detail }} 但有两个例外:1. main 函数是特殊的可以不写 return 语句,默认会自动帮你 `return 0;`。2. 具有 co_return 或 co_await 的协程函数可以不写 return 语句。
4040
41+
注意:`void`仅仅只是无返回值,而非不返回。那有没有函数确实不返回的情况呢?还真有!比如程序炸掉的时候:
42+
43+
```cpp
44+
#include <exception>
45+
46+
[[noreturn]]
47+
void func() {
48+
::std::terminate();
49+
}
50+
```
51+
52+
当程序运行到`::std::terminate()`的时候直接炸掉了,自然就不需用`return`。一个好的建议是对这种情况加上`[[noreturn]]`以辅助编译器进行优化。
53+
4154
### 接住返回值
4255

4356
## 函数的参数

0 commit comments

Comments
 (0)