Comma operator and void expression

半城伤御伤魂 提交于 2019-12-10 02:58:50

问题


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: This is not a real life example.

My question is "Is the behaviour of the code snippet well defined in C and C++?"

My take:

In C the behaviour is well defined because 6.5.17 says

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

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.

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.

Similarly in C

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: If you think the question is useless and you have got better things to do, help yourself: D.


回答1:


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.

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

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




回答2:


It's undefined behavior.

The evaluation of the left expression results in flowing off the end of a value-returning function with no return. Just because the value is discarded doesn't mean the evaluation never happened.




回答3:


It's clearly undefined. C99 §6.3.2.2 says, "(A void expression is evaluated for its side effects.)" So the function is evaluated and does flow off the end. There's no get out of jail free card.



来源:https://stackoverflow.com/questions/5401062/comma-operator-and-void-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!