Skip to content

Commit eb787cd

Browse files
authored
Merge pull request #68 from GoodenoughPhysicsLab/dev
update functions.md: noreturn
2 parents 1fe985e + b7fc273 commit eb787cd

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

docs/functions.md

+11
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,19 @@ void compute()
3636
```
3737

3838
> {{ icon.warn }} 对于返回类型不为 `void` 的函数,必须写 `return` 语句,如果漏写,会出现可怕的未定义行为 (undefined behaviour)。编译器不一定会报错,而是到运行时才出现崩溃等现象。建议 GCC 用户开启 `-Werror=return-type` 让编译器在编译时就检测此类错误,MSVC 则是开启 `/we4716`。更多未定义行为可以看我们的[未定义行为列表](undef.md)章节。
39+
3940
> {{ icon.detail }} 但有两个例外:1. main 函数是特殊的可以不写 return 语句,默认会自动帮你 `return 0;`。2. 具有 co_return 或 co_await 的协程函数可以不写 return 语句。
4041
42+
`void`只是说明该函数没有返回值,返回还是能返回的。相当于你出门跑了一趟,但是没有带任何东西回家,并不代表你无法回家死外面了。也有一种真无法返回的函数,一旦调用了,就“无期徒刑”直到死亡都无法离开:
43+
44+
```cpp
45+
[[noreturn]] void func() {
46+
std::terminate();
47+
}
48+
```
49+
50+
`std::terminate()`的效果是终止当前进程。而我们的函数`func`所有可能的分支都会走向`std::terminate()`,一旦调用了`std::terminate()`,程序就退出了,不可能再执行下面的语句,这种函数叫做“无返回函数”。C语言可以用`noreturn`关键字修饰,而现代C++可以用`[[noreturn]]`修饰,提醒编译器这是一个不可能正常返回的函数,从而帮助它优化和诊断你的程序。例如:`std::exit``throw``std::terminate``std::abort``while (1)`都会让函数变成无返回函数(除非有其他能正常返回的分支)。
51+
4152
### 接住返回值
4253

4354
## 函数的参数

0 commit comments

Comments
 (0)