函数中的局部变量在再次调用函数时保持其值

时间:2015-11-19 02:23:37

标签: c

在这个程序中,第一次调用0时打印p()(我意识到它可能只是在某些系统上打印垃圾)。

但第二次调用2时,即使再次声明y,也会打印y。似乎保留p()首次调用void p () { int y; printf ("%d ", y); y = 2; } void main () { p(); p(); } 时的值。

我很困惑为什么。有人可以解释一下吗?还有我如何修改主要功能,使其不这样做?

{{1}}

2 个答案:

答案 0 :(得分:0)

http://en.cppreference.com/w/c/language/storage_duration#Storage_duration

最简单的方法是更改​​存储持续时间或变量。但另一种方法是使用函数参数和返回值来传递状态信息。静态存储持续时间在多线程程序中可能存在问题,这使得替代解决方案通常更具吸引力。

编辑:对。我阅读并理解与提问完全相反的问题。关于未初始化值的评论是正确答案。这意味着在没有初始化的情况下,变量具有随机值,该值是从一些随机的先前操在这种情况下,随机值恰好与先前调用相同函数的变量相同。

答案 1 :(得分:0)

大多数C编译器在堆栈中存储局部变量。你的代码行为如下。

- >第一次打电话给p()

1. **int y;** push y in top of stack. (here value y is 0 or garbage according to compiler because it take value of is memory location).
2. **printf ("%d ", y);** print value of y location.
3. **y = 2;** change value of y location with 2.
4. end of function scope of y finish ( i assume you know a variable scope in c) and pop from stack but not reset value of that location.

- >第二次调用p()

1. **int y;** push y in top of stack (memory location allocated of variable y is same as first call p() memory allocation of y so that here value y is 2 because in first call we set value 2 in this location)
2. **printf ("%d ", y);** print value of y location. 

这就是为什么这里2打印第二次调用p()。

供参考,请参阅以下代码,我在此代码中打印变量的值和内存地址。

void p()

{

int y;

printf(“y =%d \ n”的值,y);

printf(“y =%p \ n”的地址,& y);

y = 2;

}

void q() {

int x;

printf(“x的值=%d \ n”,x);

printf(“地址x =%p \ n”,& x);

x = 8;

}

void main()

{

P();

Q();

P();

}

相关问题