Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a struct in accordance with C programming language standards

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {   bool flag;   short int value;   double stuff; } MY_TYPE;  void function(void) {   MY_TYPE a;   ...   a = { true, 15, 0.123 } } 

Is this the way to declare and initialize a local variable of MY_TYPE in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?

Update I ended up having a static initialization element where I set every subelement according to my needs.

like image 384
cringe Avatar asked Dec 01 '08 13:12

cringe


People also ask

How do you initialize a struct in C?

Use Individual Assignment to Initialize a Struct in C Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately.

How do you initialize a structure?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

Can you initialize in struct definition?

No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).

How do you initialize a struct in a string?

You can't initialize any members in a struct declaration. You have to initialize the struct when you create an instance of the struct. struct my_struct { char* str; }; int main(int argc,char *argv[]) { struct my_struct foo = {"string literal"}; ... }


2 Answers

In (ANSI) C99, you can use a designated initializer to initialize a structure:

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 }; 

Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)

like image 103
philant Avatar answered Sep 22 '22 05:09

philant


You can do it with a compound literal. According to that page, it works in C99 (which also counts as ANSI C).

MY_TYPE a;  a = (MY_TYPE) { .flag = true, .value = 123, .stuff = 0.456 }; ... a = (MY_TYPE) { .value = 234, .stuff = 1.234, .flag = false }; 

The designations in the initializers are optional; you could also write:

a = (MY_TYPE) { true,  123, 0.456 }; ... a = (MY_TYPE) { false, 234, 1.234 }; 
like image 40
CesarB Avatar answered Sep 24 '22 05:09

CesarB