I came across some code similar to this:
struct Struct
{
int a;
int b;
};
int main()
{
struct Struct variable = { }; // ???
variable.a = 4;
variable.b = 6;
}
This is strange. The initialisation of a
and b
could be happening in the initialiser (between the curly braces). But they aren't. What's the point in keeping the = { }
part? The following should be just fine, right?
struct Struct variable;
Or is it? Is having an empty initialiser in any way different to having no initialiser?
My small C handbook states that
For variables without an initialiser: All variables with static scope are implicitly initialised with zero (that is all bytes = 0). All other variables have undefined values!
The caveat is that this is not explicitly mentioning struct
s.
When is the condition of being without an initialiser met for the fields of a struct
? I made the following test:
#include <stdio.h>
struct Struct
{
int a;
int b;
};
int main()
{
struct Struct foo = { };
foo.a = 4;
struct Struct bar;
bar.a = 4;
printf("with list:\t %i\n", foo.b);
printf("without list:\t %i\n", bar.b);
}
With the result being:
with list: 0
without list: 32765
This is confusing. The struct
without an initialiser list did not get initialised with 0, contrary to what my little C book says.
How do these initialiser lists work with structs exactly?