I'm trying to define a static structure and initialize its values once when it is declared, but I'm not really sure how I would do so.
I'm calling a function in a loop, and I want to initialize a timespec
(specifically the tv_sec
value) to 0
(sort of a default value) the first time the function is called, but never again.
I know I can do this with integers and other simple data types by doing:
static int foo = 0
But I want to do the same with with a structure, so its not so simple.
Essentially, I want to do this: static struct timespec ts.tv_sec = 0;
But, that illegal, so I need to know the legal form (if it exists).
Help?
Aggregate objects, like structs or arrays, are initialized with = { ... }
initializers. You can either supply initializers for consecutive members of the struct beginning with the first, or use C99 tagged approach
static struct timespec ts = { .tv_sec = 0 };
Note BTW that = { ... }
approach is more universal than it might seem at first sight. Scalar objects can also be initialized with such initializers
static int foo = { 0 };
Also note that = { 0 }
will zero out all data fields in the aggregate object, not just the first one.
Finally keep in mind that objects with static storage duration are always zero-initialized automatically, meaning that if you just declare
static struct timespec ts;
you are already guaranteed to end up with zero-initialized object. No need to do it explicitly.
A static object, no matter if it's a struct, union, array or basic type is always zero initialized in the absence of an explicit initializer. Just use
static struct timespec foo;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With