Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Declaration of a structure

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?

like image 446
Nealon Avatar asked Jan 14 '23 01:01

Nealon


2 Answers

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.

like image 141
AnT Avatar answered Jan 17 '23 16:01

AnT


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;
like image 35
Jens Avatar answered Jan 17 '23 14:01

Jens