Static structure declaration

I am trying to define a static structure and initialize its values ​​once when it is declared, but I'm not quite sure how to do this.

I call the function in a loop, and I want to initialize the timespec value (in particular, the timespec value) to 0 (default sort) on the first call to the function, but never again.

I know I can do this with integers and other simple data types: static int foo = 0

But I want to do the same with the structure, so its not so simple.

Essentially, I want to do this: static struct timespec ts.tv_sec = 0; But, this is illegal, so I need to know the legal form (if it exists).

reference

+4
source share
3 answers

Aggregate objects, such as structures or arrays, are initialized with initializers = { ... } . You can either provide initializers for consecutive members of the structure starting with the first, or use the approach labeled C99

 static struct timespec ts = { .tv_sec = 0 }; 

Please note that the approach = { ... } more universal than it might seem at first glance. Scalar objects can also be initialized with such initializers.

 static int foo = { 0 }; 

Also note that = { 0 } will reset all data fields in the aggregated object, not just the first one.

Lastly, keep in mind that objects with a static storage duration are always null automatically initialized, which means that if you simply declare

 static struct timespec ts; 

you are guaranteed to get a zero initialized object. There is no need to do this explicitly.

+7
source

A static object, regardless of whether it is a structure, union, array, or base type, is always zero, initialized in the absence of an explicit initializer. Just use

 static struct timespec foo; 
+1
source

Instead of initializing with an "invalid" value, you can simply use another variable:

 static struct timespec ts; static int ts_initialized = 0; if (!ts_initialized) { init_ts(&ts); ts_initialized = 1; } 

Benefits:
1. Somewhat more understandable.
2. No need to find a "magic" value that will never be used.

0
source

Source: https://habr.com/ru/post/1488352/


All Articles