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:
What is the proper way to handle such a scenario in C11?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With