有人可以解释这个C输出吗?

时间:2012-11-29 15:19:05

标签: c

  

可能重复:
  Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

#include<stdio.h>
void call(int,int,int);

int main(){

int a=10;
call(a,a++,++a);
return 0;   
}

void call(int x,int y,int z){
printf("x=%d y=%d z=%d\n",x,y,z);
}

此代码在运行时给出输出12 11 12。有人可以解释这是怎么发生的吗?

2 个答案:

答案 0 :(得分:3)

您的代码行为为undefined,因为您在sequence points之间更改了a两次:

call(a,a++,++a);

答案 1 :(得分:3)

behaviour is undefined,因为在两个序列点之间更改变量两次。

c99 standard : 5.1.2.3 Program execution

2

"Accessing a volatile object, modifying an object, modifying a file, or calling a function
that does any of those operations are all `side effects` which are changes in the state of
the `execution environment`. Evaluation of an expression may produce side effects. At
certain specified points in the execution sequence called `sequence points`, all side effects
of previous evaluations shall be complete and no side effects of subsequent evaluations
shall have taken place."

在这里,您要在两个序列点之间修改变量a两次。

扩展编辑:如果您已经了解这些概念并且考虑,逗号运算符是一个序列点,那么它应该作为well defined程序运行。然后您使用错误,这里的函数调用是comma separator而不是comma operator