如何根据条件简明地分配给结构的成员?

时间:2016-08-25 05:04:00

标签: c if-statement struct initialization c11

我有一些看起来像这样的代码:

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 */
    }
}

我考虑的选项:

  • 最简单的方法是拥有一个分配给每个成员并调用它的函数。我应该只希望编译器优化该调用吗?
  • 定义一个宏以明确避免函数调用开销。
  • 长途跋涉。

在C11中处理这种情况的正确方法是什么?

3 个答案:

答案 0 :(得分:7)

只需编写初始化成员的函数,或者如果您需要(基于意见),请使用MACRO。

顺便说一句,我个人这样做:

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

或者只使用三元运算符。请记住,您关心可读性并始终牢记:

  

朴素是一种美德!

我真的认为在这个阶段担心优化将会成为不成熟优化的受害者,因为我怀疑它会成为瓶颈。

一般来说,如果你想优化你的代码,配置你的代码(当它运行优化标志时,许多人不知道这一点,我就是其中之一:Poor performance of stl list on vs2015 while deleting nodes which contain iterator to self's position in list),找到瓶颈并尝试优化这个瓶颈。

答案 1 :(得分: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;
// ...

请不要担心一个函数调用开销。

答案 2 :(得分:4)

我同意已发布的答案(@gsamaras和@Arun)。我只是希望展示另一种我发现有用的方法。

方法是使用两个(或更多)相关的初始化值制作一些常量,然后根据一个(或多个)条件进行简单的赋值。

简单示例:

#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;
}