在C局部变量的默认值是一个垃圾的价值,对不对?那么,为什么我总是得到相同的输出? [英] The default value of a local variable in c is a garbage value,right? Then why am always getting same output?
本文介绍了在C局部变量的默认值是一个垃圾的价值,对不对?那么,为什么我总是得到相同的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void func();
int main()
{
func();
func();
func();
}
void func()
{
int a;
printf("%d\n",++a);
}
当我运行GCC编译这个C code口输出作为了1 2 3;为什么出现这种情况,而无需使用静态
关键字?
When I run this C code in GCC compiler I got output as 1 2 3; why this happen without using the static
keyword?
推荐答案
有两种情况考虑:
- 如果局部变量
静态
,它是用零初始化;静态
指针类型的变量设置为NULL
- 如果局部变量是自动的,它没有被初始化的。从这些变量读不首先分配给它是不确定的行为。
- If the local variable is
static
, it is initialized with zeros;static
variables of pointer type are set toNULL
- If the local variable is automatic, it is not initialized at all. Reading from such variable without assigning to it first is undefined behavior.
这篇关于在C局部变量的默认值是一个垃圾的价值,对不对?那么,为什么我总是得到相同的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文