initializing struct on declaration

Code:
1
2
3
4
struct foo {
    char label[64];
    int state;
} bar[3] = { };


Will the above code ALWAYS initialize to 0 all objects:
bar[0].label
bar[0].state
bar[1].label
bar[1].state
bar[2].label
bar[2].state


Using gcc and g++, it does in my testing
But was wondering if it can be unsafe under some circumstances.

I even tried without = { } and it is still initialized to 0 for all objects!
Last edited on
Yes, aggregate initialization with all initializers omitted (which is what = { } is) guarantees that your members will be initialized to zeroes

http://en.cppreference.com/w/cpp/language/aggregate_initialization


I even tried without = { } and it is still initialized to 0 for all objects!

Without = { }, you are using default initialization, which is only guaranteed to zero them out if your object is static (or thread-local), e.g. if you're defining this at file scope.

http://en.cppreference.com/w/cpp/language/zero_initialization
Last edited on
Thank you for the references
Last edited on
One other question
when declared in header, what is the easiest way to initialize it in code?
For now I do using a void function called on program start.
wondering if there is an easier way to do it like for regular variables
wondering if there is an easier way to do it like for regular variables

variables of struct type are no different from variables of any other type.
1
2
3
4
5
6
7
8
9
10
struct foo {
    char label[64];
    int state;
};
int main()
{
    foo a;
    foo b = {};
    a.state=7;
}
yes, as I said, I am using a function already
the struct is in a header shared among many source files

So, I need to call a function to initialize it
Thanks
Topic archived. No new replies allowed.