简体   繁体   English

表达式中的C序列点包含函数调用和后递增

[英]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? 它是保证是01 ,还是00 ,在声明之后发生了两个后增量?

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. 根据C99 C11,两者中的附录C,在调用所有参数并且&&运算符的第一个操作数的末尾之后,在调用函数时有一个序列点。

So you're doubly protected or, as we say in Australia, if the sharks don't get you, the crocodiles will (a) . 所以你受到双重保护,或者正如我们在澳大利亚所说的那样,如果鲨鱼没有得到你,鳄鱼会(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一个(为了便于阅读,略微改述):

C11: 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 . 所以你的代码片段定义明确,输出结果为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. (a)实际上,我不认为澳大利亚的任何人都可能会说,除了史蒂夫欧文,他既不是鲨鱼也不是鳄鱼,并且可能会欣赏这种讽刺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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