gpt4 book ai didi

c++ - 如果 void 类型的函数什么都不返回会怎样?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:16 24 4
gpt4 key购买 nike

假设我们有这样的功能

void test() {return;}

它是正确的 C 代码吗?我刚刚在 mingw 中测试了它,编译器什么也没说,对于

void test() {return 1;}

所以我想我的编译器确实过时了。

在给定情况下,在 C/C++ 中应该发生什么?

编辑:

return 1; 给我一个警告。这是否意味着 return; 是正确的?

最佳答案

C++11(ISO/IEC 14882:2011) §6.6.3 返回语句

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 void, a constructor, or a destructor. A return statement with an expression of non-void type can be used only in functions returning a value

C11(ISO/IEC 9899:201x) §6.8.6.4 返回语句

A return statement with an expression shall not appear in a function whose return type is void. A return statement without an expression shall only appear in a function whose return type is void.

但是,C89/C90只限制了一半:

C89/C90(ISO/IEC 9899:1990) §3.6.6.4 返回语句

A return statement with an expression shall not appear in a function whose return type is void .

在 C11 Forward 部分,它列出了第三版(即 C11)和第二版(即 C99)中的所有主要更改。最后一个是:

Major changes in the second edition included:

...

— return without expression not permitted in function that returns a value (and viceversa)

这意味着从C99开始,函数返回类型的约束变化发生了变化。

关于c++ - 如果 void 类型的函数什么都不返回会怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17530279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com