我可以重新初始化全局变量以覆盖其在C中的值吗?

时间:2014-03-29 08:39:16

标签: c global-variables

有谁知道为什么我的程序在下面的情况下打印-69?我希望它能用C语言打印未初始化的原始数据类型的默认/垃圾值。谢谢。

#include<stdio.h>

int a = 0; //global I get it
void doesSomething(){
   int a ; //I override global declaration to test.
   printf("I am int a : %d\n", a); //but I am aware this is not.
    a = -69; //why the function call on 2nd time prints -69?
}

int main(){
  a = 99; //I re-assign a from 0 -> 99
  doesSomething(); // I expect it to print random value of int a
  doesSomething(); // expect it to print random value, but prints -69 , why??
  int uninitialized_variable;
  printf("The uninitialized integer value is %d\n", uninitialized_variable);
}

2 个答案:

答案 0 :(得分:4)

您所拥有的是未定义的行为,您无法事先预测未定义行为的行为。

然而,在这种情况下,它很容易理解。 a函数中的局部变量doesSomething放置在堆栈上的特定位置,并且该位置在调用之间不会更改。所以你所看到的是之前的价值。

如果你之间有其他东西,你会得到不同的结果。

答案 1 :(得分:2)

是啊..你的函数重用两次相同的内存段。所以,第二次调用“doesSomething()”时,变量“a”仍然是“随机”..例如下面的代码填充调用两个调用之间的另一个函数,你的操作系统将为你提供不同的段:

#include<stdio.h>

int a = 0; //global I get it
void doesSomething(){
   int a; //I override global declaration to test.
   printf("I am int a : %d\n", a); //but I am aware this is not.
    a = -69; //why the function call on 2nd time prints -69?
}

int main(){
  a = 99; //I re-assign a from 0 -> 99
  doesSomething(); // I expect it to print random value of int a
  printf( "edadadadaf\n" );
  doesSomething(); // expect it to print random value, but prints -69 , why??
  int uninitialized_variable;
  printf("The uninitialized integer value is %d\n", uninitialized_variable);
}