uffu
uffu

Reputation: 51

Initialize C struct vs assign members

I want to know what is the best practice for initializing struct members.

For instance, for this struct which option is better and why? In terms of especially readability and performance?

typedef struct
{
    int a;
    char b;
} str_t;

Option 1

void foo1(int param_a, char param_b)
{
    str_t str = {
        .a = param_a,
        .b = param_b
    };
    ...
} 

What will be the omitted members, zero or garbage in the stack?

Option 2

void foo2(int param_a, char param_b)
{
    str_t str;
    str.a = param_a;
    str.b = param_b;
    ...
} 

This option would allow zero initialization (with = {0};). But I guess that would force runtime assignment, right?

Bonus

Also, would it be different for constant values?

void foo1()
{
    str_t str = {
        .a = 5,
        .b = 10
    };
    ...
} 
void foo2()
{
    str_t str;
    str.a = 5;
    str.b = 10;
    ...
} 

Upvotes: 2

Views: 170

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754090

Option 1 works. Unmentioned elements will be 'zero initialized' — given a default value which is zero. It works correctly with static variables in functions. It should be your first choice.

Option 2 also works. It might be slower. It is wholly inappropriate for static variables; the assignments occur on each call to the function.

Bonus: Using constants instead of variables in the initializers makes very little difference to the analysis — option 1 using designated initializers is the best way of doing it.

Upvotes: 2

Related Questions