-1

While running this I found the output to be: 4 4. Could not understand the cause.

int i = 2;
printf("%d %d", ++i, ++i);
Shivendra
  • 1,076
  • 2
  • 12
  • 26
  • A function cannot be called before its arguments are evaluated, can it? – R. Martinho Fernandes Oct 31 '13 at 10:27
  • 2
    @R.MartinhoFernandes: no, but the values of its arguments can be set in stone before the side-effects of its argument expressions are applied, because the only sequence point in sight is *after* evaluation but *before* the function call. Hence `3 3`, `3 4`, `4 3` and `4 4` are all vaguely plausible outputs for this code, although ofc it has undefined behavior so anything is permitted. – Steve Jessop Oct 31 '13 at 10:41

1 Answers1

4

What you have experienced is Undefined behavior. Please read about sequence points. Comma is a separator in function calls not an operator.

A sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete. The sequence points listed in the C standard are:

at the end of the evaluation of a full expression (a full expression is an expression statement, or any other expression which is not a subexpression within any larger expression); at the ||, &&, ?:, and comma operators; and at a function call (after the evaluation of all the arguments, and just before the actual call).

The Standard states that

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 accessed only to determine the value to be stored.

Sadique
  • 22,572
  • 7
  • 65
  • 91