逗号运算符和 void 表达式 [英] Comma operator and void expression

查看:42
本文介绍了逗号运算符和 void 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个代码片段 1

I came across this code snippet 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

In C the behaviour is well defined because 6.5.17 says

逗号运算符的左操作数被计算为void 表达式;求值后有一个序列点

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

In C++03 the behaviour is well defined because 5.18 says

一对用逗号分隔的表达式从左到右求值,左边表达式的值被丢弃.

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 部分)也说

However C++03 (in section 6.6.3) also says that

从函数的末尾流出相当于没有值的返回;这会导致返回值的函数中出现未定义的行为.

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 中类似

如果控制到达非空函数的结尾(})(main() 除外),则行为未定义.

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

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

So taking all these points into consideration I can't judge the actual behaviour. What do you people think?

P.S:如果你觉得这个问题没用,你还有更好的事情要做,请自救:D.

推荐答案

我拥有的 C 规范 (C99 TC3) 说

The C spec I have (C99 TC3) says

如果到达终止函数的 },并且调用者使用了函数调用的值,则行为未定义.

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

被称为作为 void 表达式求值"的表达式的值被丢弃.所以在 C 的情况下,没有未定义的行为.它在旧 C 中可能有所不同(如果我没记错的话,有些细节是).

The value of an expression that's said to be "evaluated as a void expression" is discarded. So in the C case, there is no undefined behavior. It may have been different in old C (some details are, if I remember correctly).

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

The situation for C++ is slightly different than for C, because C++ supports class objects with constructor and destructors as return values and having them operate on uninitialized memory can't be guaranteed to work well. Perhaps this contributed to the different rules for C++.

这篇关于逗号运算符和 void 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆