I recently came across a post What is the correct answer for cout << c++ << c;? and was wondering whether the output of
int c = 0;
printf (
This program exhibits a combination of both unspecified behavior and undefined behavior. Starting with the unspecified behavior, the draft C99 standard in section6.5
paragraph 3
says:
The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
It also says except as specified later and specifically cites function-call ()
, so we see that later on the draft standard in section 6.5.2.2
Function calls paragraph 10
says:
The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.
So we do not know whether the read of C or the evaluation of C++ will happen first at this line of code:
printf ("%d %d", c++, c);
furthermore, in section 6.5.2.4
Postfix increment and decrement operators paragraph 2
says:
[...] After the result is obtained, the value of the operand is incremented. [...] The side effect of updating the stored value of the operand shall occur between the previous and the next sequence point.
So all we know is that when performing the post increment c
will be updated after its value is read but before the next sequence point which is right before printf
is called but nothing else. As for the undefined behavior, if we look at section 6.5
paragraph 2
from the draft standard, is says:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
In the printf
expression c
s prior value is being read in order to evaluate both C++ and C and so we now are in undefined territory.