gpt4 book ai didi

c - 在 C 中,如果 foo 的返回类型为 void,表达式 foo() 是否可以用作空表达式?

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:41 25 4
gpt4 key购买 nike

关于返回语句,Microsoft Visual Studio 文档说

Syntax:

return expression;

其中表达式被标记为可选。继续

The value of expression, if present, is returned to the calling function. If expression is omitted, the return value of the function is undefined.

这很清楚,但另一方面,还有一个空表达式的概念。这让我很困惑。考虑到空表达式不是什么都没有,而是一个空的表达式,我想如果我们有一个函数

void foo(void)
{
return;
}

那么可以在任何允许空表达式的地方使用表达式 foo()。例如代码的行为

unsigned int i=0;
for(foo();i<10;i++) printf("%u",i);

将被定义。我知道这可能没有什么实际意义,但我想了解为什么在这种情况下,空表达式不是表达式。

最佳答案

这叫做空表达式。您可以像以前一样在 for 中使用 void 表达式。 void 表达式只做它的副作用,即调用函数。

事实上,如果 for 的第一个子句是任何类型的表达式,它被评估为一个 void 表达式:

C99 6.8.5.3 The for statement

... If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.

C99 6.3.2.2 void

The (nonexistent) value of a void expression(an expression that has type void) shall not be used in any way, and implicit or explicit conversions (except to void) shall not be applied to such an expression. If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A void expression is evaluated for its side effects.)

关于c - 在 C 中,如果 foo 的返回类型为 void,表达式 foo() 是否可以用作空表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19475750/

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