Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C sequence points within expression containing function calls and post-increments

What is printed by the following code?

#include <stdio.h>


int f(int x) { printf("%d", x); return 1; }

int main() {
    int i = 0;
    f(i++) && f(i++);
}

Is it guaranteed to be 01, or could it be 00 with both of the post-increments happening after the statement?

like image 424
Neil G Avatar asked Nov 16 '25 19:11

Neil G


1 Answers

As per C99 and C11, appendix C in both, there is a sequence point at the call to a function, after all the arguments have been evaluated and at the end of the first operand of the && operator.

So you're doubly protected or, as we say in Australia, if the sharks don't get you, the crocodiles will (a).

The wording is slightly different between the two iterations of the standard but they have the same effect. The C11 one is (slightly paraphrased for readability):

C11:

The following are the sequence points described earlier:

  • Between the evaluations of the function designator and actual arguments in a function call and the actual call.
  • Between the evaluations of the first and second operands of the following operators: '&&' '||' '?' ','.

The short-circuiting nature of && also means that the left hand side of the expression will be evaluated first.

So your snippet is well defined, and the output will be 01.


(a) Actually, I don't think anyone in Australia would be likely to say that, other than maybe Steve Irwin, who was gotten by neither shark nor crocodile, and would probably appreciate the irony of such.

like image 191
paxdiablo Avatar answered Nov 19 '25 09:11

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!