简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM