Question

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;
Was it helpful?

Solution

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top