我正在阅读一本关于 C 语言编程常见问题解答的书。 这是本书的段落
Automatic variables are variables defined inside a function or block of code without the static keyword. These variables have undefined values if you don’t explicitly initialize them. If you don’t initialize an automatic variable, you must make sure you assign to it before using the value.
这是我的代码:
#include <stdio.h>
int main (int argc, const char * argv[])
{
{
int x;
printf("%d", x);
}
}
printf
的结果是0,为什么要初始化变量?
最佳答案
对于静态和全局变量,它是 0;默认情况下不初始化自动变量。
在c语言中,非静态局部变量没有默认值。变量在成为变量之前保存内存中的所有内容。在 c 语言中使用非静态局部变量之前(或至少在将其与其他变量进行比较之前),最好始终对其进行初始化。此外,最好假设没有默认值,因为这因语言和硬件而异。
阅读更多:http://wiki.answers.com/Q/What_is_the_default_value_of_integer_in_c#ixzz1iaij7hRK
关于c - 非静态变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8743445/