Initialization of static variables in C [duplicate]

让人想犯罪 __ 提交于 2019-12-09 23:13:16

问题


Possible Duplicate:
The initialization of static variable in C

I know that either global variables or static are automatically initialized with zero in C. However, I'm not sure if both or only one of them are initialized. Note that I'm not talking about variables defined in functions but globally in the .c file.

So which of the following variables are automatically initialized with zero?

static struct mystruct var1;
struct mystruct var2;
static struct { int x; int y; } var3;

回答1:


C FAQ.




回答2:


I ran the following code in codepad

struct mystruct { int a; };

static struct mystruct var1;
struct mystruct var2;
static struct { int x; int y; } var3;

#include <stdio.h>
void main()
{
    int x;
    printf("var1.a: %d\n", var1.a);
    printf("var2.a: %d\n", var2.a);
    printf("var3.x: %d\n", var3.x);
    printf("var3.y: %d\n", var3.y);
    printf("x: %d\n", x);
}

results:

var1.a: 0
var2.a: 0
var3.x: 0
var3.y: 0
x: 1075105060

Regardless, I don't like making assumptions about initialisation but YMMV.



来源:https://stackoverflow.com/questions/4398609/initialization-of-static-variables-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!