2014-03-29 54 views
0

有没有人知道我的程序为什么在下面的情况下打印-69?我期望它用C语言打印未初始化原始数据类型的默认/垃圾值。谢谢。我可以重新初始化全局变量以覆盖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); 
} 

回答

4

你有什么是不确定的行为,你无法事先预测的未定义行为的行为。

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

如果你之间已经调用了其他东西,你会得到不同的结果。

+0

:这里是流“A”与2次呼叫doesSomethnig的:让图像并作为堆栈> A =垃圾,(打印垃圾),a =(-69),退出循环,我假设自动变量被释放并且栈被清除,但是你提到的'a'位置的参数不会改变,在第二次调用doesSomething:a =垃圾,然后打印一个=>它应该打印垃圾。为什么要打印(-69),垃圾值现在在堆栈顶部,不是吗? –

2

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

#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); 
} 
在堆壳