Comma operator and void expression
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 cod开发者_如何学JAVAe 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 (exceptmain()
) 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.
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++.
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.
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.
精彩评论