gpt4 book ai didi

c++ - 逗号运算符和 void 表达式

转载 作者:可可西里 更新时间:2023-11-01 17:39:43 26 4
gpt4 key购买 nike

我遇到了这个代码片段1

int return_printChar1()
{
// code
// oops! no return statement
}
int return_printChar2()
{
// code
return printf("Return");
}
int main()
{
int i;
// some more code
i = return_printChar2();
if((return_printChar1(),i))
{
printf ("Gotcha");
}
}

1:这不是现实生活中的例子。

我的问题是“C 和 C++ 中是否明确定义了代码片段的行为?

我的看法:

在 C 中,行为定义明确,因为 6.5.17

The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation

在 C++03 中,行为定义明确,因为 5.18

A pair of expressions separated by a comma is evaluated left-to-right and the value of the left expression is discarded.

但是 C++03(在 6.6.3 部分)也这样说

Flowing off the end of a function is equivalent to a returnwith no value; this results in undefined behavior in a value-returning function.

C 中类似

If control reaches end (}) of non-void function (except main()) the behaviour is undefined.

因此,考虑到所有这些要点,我无法判断实际行为。大家怎么看?

P.S:如果您认为这个问题没有用,并且您有更好的事情要做,请帮助自己:D。

最佳答案

我的 C 规范 (C99 TC3) 说

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

被称为“被评估为空表达式”的表达式的值被丢弃。所以在 C 的情况下,没有未定义的行为。它在旧的 C 中可能有所不同(如果我没记错的话,一些细节是)。

C++ 的情况与 C 略有不同,因为 C++ 支持将构造函数和析构函数作为返回值的类对象,并且不能保证让它们在未初始化的内存上运行。也许这导致了 C++ 的不同规则。

关于c++ - 逗号运算符和 void 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5401062/

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