user2296177 user2296177 - 1 year ago 105
C Question

How can I concisely assign to the members of a struct depending on a condition?

I have code that looks like this:

struct mystruct
{
/* lots of members */
};

void mystruct_init( struct mystruct* dst, int const condition )
{
if ( condition )
{
/* initialize members individually a certain way */
}
else
{
/* initialize members individually another way */
}
}


Options I'm considering:


  • Simplest would be to have a function that assigns to every member and call that. Should I simply hope the compiler optimizes that call away?

  • Define a macro to explicitly avoid the function call overhead.

  • Write everything the long way.



What is the proper way to handle such a scenario in C11?

Answer Source

Just write a function that initializes a member, or if you want (opinion based), use a MACRO.

By the way, I would personally do it like this:

void mystruct_init( struct mystruct* dst, int const condition )
{
    if ( condition )
        init_first_way(..);
    else
        init_second_way(..);
}

or just use the ternary operator. Remember, you care about readability and always have in mind:

Simplicity is a virtue!


I really think worrying about optimization at this stage will make a victim of immature optimization, since I doubt it will be the bottleneck.

In general, if you want to optimize your code, profile your code(while it runs with optimization flags, many people do not know this, I was one of them: Poor performance of stl list on vs2015 while deleting nodes which contain iterator to self's position in list), find the bottleneck and try to optimize that bottleneck.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download