C-整型变量的假值

C-整型变量的假值,c,C,下面代码中的输出非常神秘 #include <stdio.h> void funktion(int x) {} void test() { int foo; printf("test = %d\n", foo); } int main() { test(); funktion(5); test(); return 0; } #包括 无效函数(int x){} 无效测试(){ int foo; printf(“测试=%d\n”,

下面代码中的输出非常神秘

#include <stdio.h>

void funktion(int x) {}

void test() {
    int foo;
    printf("test = %d\n", foo);
}

int main() {
    test();
    funktion(5);
    test();

    return 0;
}
#包括
无效函数(int x){}
无效测试(){
int foo;
printf(“测试=%d\n”,foo);
}
int main(){
test();
功能(5);
test();
返回0;
}

为什么要用funktion()参数的值初始化foo变量?我不明白为什么foo var是由函数参数初始化的。我知道我可以用一个显式的初始化来修复它,但我想理解其中的奥秘。谢谢

我在
main()
函数中添加了注释,解释了为什么会这样。顺便说一下,您处于未定义的行为领域,不同的平台可能会产生不同的结果

int main() {
    // no return, no parameter, one local variable of type int.
    // This pushes an int on the stack, uninitialized (the local variable).
    test();
    // Stack pointer is back to where it was.

    // no return, one int parameter, no local variables.
    // This pushes an int with value=5 on the stack (the parameter).
    funktion(5);
    // Stack pointer is back to where it was.

    // no return, no parameter, one local variable of type int.
    // This pushes an int on the stack, uninitialized (the local variable). 
    // Previous value of that memory comes from funktion() call.
    test();
    // Stack pointer is back to where it was.

    return 0;
}

未定义行为是使用未初始化变量。从未初始化变量读取值是未定义行为。它可以是任何东西。在C语言中,它不是未定义的行为。但未初始化的局部变量(如
foo
)的值是不确定的。@EugeneSh。我想是的,但我不是100%肯定。我认为只有当不定值是陷阱值时才是UB(对于整数来说永远不会是)。@Someprogrammerdude唯一保证没有陷阱表示的类型是“unsigned char”。根据实施情况,任何其他类型都可以。在大多数人可能遇到的系统(即x86 Linux或Windows)上,通常没有。有符号整数可能有陷阱表示,例如,如果它使用一个人的恭维表示,并且不支持负0。感谢您对这个谜的解释!