Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have some 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?

like image 972
user2296177 Avatar asked Dec 02 '22 12:12

user2296177


2 Answers

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.

like image 52
gsamaras Avatar answered Dec 05 '22 01:12

gsamaras


I do not think that there is any clear rule here. To me, it depends on the taste of the author.

Two obvious ways are:

// initialize members that are independent of 'condition'

if (condition) {
  // initialize members one way
}
else {
  // initialize members another way
}

The same may be written as:

// initialize members that are independent of 'condition'

// initialize members based on 'condition'
dst->memberx = condition ? something : something_else;
// ...

Please do not worry about one function call overhead.

like image 20
Arun Avatar answered Dec 05 '22 02:12

Arun