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



有人知道为什么我的程序在下面打印-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 : %dn", 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 %dn", uninitialized_variable);
}

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

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

是的…你的函数重用两次相同的内存段。所以,第二次调用"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 : %dn", 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( "edadadadafn" );
  doesSomething(); // expect it to print random value, but prints -69 , why??
  int uninitialized_variable;
  printf("The uninitialized integer value is %dn", uninitialized_variable);
} 

相关内容

  • 没有找到相关文章

最新更新