如何根据条件简洁地给结构体成员赋值?

4

我有一些类似这样的代码:

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中,如何正确处理这种情况?


你的代码没有问题。可读性很重要。你可以将一些行提取出来,例如 dst->foo = condition ? 5 : 7;,但是请考虑哪个选项能够更明显地告诉读者正在发生什么以及为什么。 - M.M
1
在每个if分支中考虑使用“复合字面量”和“指定初始化器”:*dst = (struct mystruct) { .member1 = value1, .member2 = value2, … }; - Jonathan Leffler
如果struct需要是const,你可以创建一些包含不同初始化列表的宏,然后在它们之间使用#ifdef。虽然不太美观,但没有其他选择。 - Lundin
3个回答

7

请编写一个函数来初始化一个成员变量,或者(基于个人意见)可以使用宏。

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

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


3
提及“不成熟的优化”点个赞。正如所说,过早地进行优化是万恶之源 :) [http://c2.com/cgi/wiki?PrematureOptimization] - Arun
@Arun,这不是关于优化的问题,而是关于简洁性的问题。我对编译器优化并不是很熟悉,所以我不想不必要地使用效率较低的东西。不过还是谢谢你们提醒我,让我记得在没有进行测量之前不要担心这样的事情。 - user2296177
@user2296177 做过了,看我的编辑。我感受到了你提出这个问题的原因,所以我点了赞。 - gsamaras

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;
// ...

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

1
那句话触动了我的心灵,很棒! - gsamaras

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接