How can I briefly assign structure members based on conditions?

I have a 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 */
    }
}

The options I'm considering are:

  • The easiest way would be to have a function that assigns to each member and calls it. Should I just hope the compiler optimizes the call?
  • Define a macro to explicitly avoid function calls.
  • Write everything long.

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

+4
source share
3 answers

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

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

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

. , :

- !


, , , .

, , ( , , : stl vs2015 , ), .

+7

, . .

:

// initialize members that are independent of 'condition'

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

:

// initialize members that are independent of 'condition'

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

, .

+7

I agree with the answers already posted (@gsamaras and @Arun). I just wanted to show a different approach, which I found useful several times.

The approach is to make some constants with two (or more) relevant initialization values, and then make a simple assignment based on one (or more) conditions.

A simple example:

#include<stdio.h>
#include <string.h>

struct mystruct
{
  int a;
  float b;
};

const struct mystruct initializer_a = { 1, 3.4 };
const struct mystruct initializer_b = { 5, 7.2 };

int main (void)
{
  int condition = 0;
  struct mystruct ms = condition ? initializer_a : initializer_b;
  printf("%d %f\n", ms.a, ms.b);
  return 1;
}
+4
source

Source: https://habr.com/ru/post/1652404/


All Articles