gpt4 book ai didi

c - 非 void 函数中的空返回,是未定义的行为吗?

转载 作者:太空狗 更新时间:2023-10-29 16:56:33 25 4
gpt4 key购买 nike

在阅读了关于控制到达非 void 函数的末尾 主题的答案后,我没有看到任何答案专门针对以空 退出非 void 函数的情况返回语句:

int return_integer() { return; }  // empty return in non-void function

到目前为止我在 C standard 中发现了什么是:

6.8.6.4 The return statement

Constraints

  1. 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.

标准引述说明了我们应该void 和非void 函数的return 语句做什么,当我们忽略约束时会发生什么在文档的其他部分提到:

6.9.1 Function definitions

  1. If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

之前的标准引用指出,如果我们使用函数的返回值,该函数在到达右花括号 () 后结束,就会发生 UB,因此我们在下面的代码中有 UB:

int UB(int x) { if (x) return x; }

printf("%d", UB(1)); // Correct
printf("%d", UB(0)); // Undefined behavior

UB(1)调用函数返回1通过if (x)下的return x;指令;在 UB(0) 调用 if (x) 条件未通过所以函数结束到达 },在此使用返回值大小写为 UB(但不在 UB(1) 中)。但是,在这种情况下会发生什么?

int UB(int x) { if (x) return; } // empty return statement

printf("%d", UB(1)); // Undefined behavior?
printf("%d", UB(0)); // Undefined behavior

在上面的代码中,调用UB(1)不满足导致UB的§6.9.1/12要求,因为函数结束没有到达 },也不返回任何值。

C 标准的哪一部分描述了这种情况?

最佳答案

int UB(int x) { if (x) return; } 

这甚至不是未定义的行为,而是违反约束。引用文本

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

从 6.8.6.4 开始是规范的,这意味着编译器不允许在不给出诊断消息的情况下让它溜走。如果它在没有给出诊断的情况下编译,则编译器不是一个符合标准的实现(不遵循语言标准)。

用简单的英语来说,这意味着:该代码甚至不应该编译。

现在,如果编译器确实生成了二进制可执行文件,即使代码违反了约束,那么所有的赌注都没有了。它不再是 C 程序,而是一些非标准程序,任何语言标准都无法保证其行为。

关于c - 非 void 函数中的空返回,是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39914040/

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