简体   繁体   English

为什么这个C程序的输出是这样的?

[英]Why the output of this C program is like this?

Why the output of the following program is 为什么以下程序的输出是

x = 10 y = 18

?

int y;
void fun(int x) {
 x+=2;
 y=x+2;
}

int main() {
 int x;
 x=10; y=11;
 fun(x);
 fun(y);
 printf("x=%d y=%d\n", x,y);
 return 0;
}

Shouldn't the output be 10 and 11 ? 输出不应该是10和11吗?

Since y is a global variable , in the first call fun(x); 由于y全局变量 ,因此在第一个调用中fun(x); y becomes 14 since x is 10 , x += 2 makes x == 12 and then y = x + 2 which gives 14 . y变为14因为x10x += 2使得x == 12 ,然后y = x + 2得出14 Then you call it with y == 14 , which makes the local x in fun() , x == 16 and then y == y + 2 which is 18 . 然后用y == 14调用它,这将使局部x进入fun()x == 16 ,然后y == y + 218

These are the states of variables before and after each of those function calls. 这些是每个函数调用之前和之后的变量状态。

PRE: x=10, y=11
 fun(x);
POST: x=10, y=14
PRE: x=10, y=14
 fun(y);
POST: x=10, y=18

If you simply rename the local variable within fun() to something other than x, it becomes less complicated. 如果您只是简单地将fun()中的局部变量重命名为x以外的其他值,则它将变得不那么复杂。

void fun(int x) {
  x+=2;
  y=x+2;
}

can be rewritten as: 可以重写为:

void fun(int local_var) {
  y=local_var+4; //y is global, local_var is thrown away at the end of this scope.
}

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

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