我有一些类似这样的代码:
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.Mif
分支中考虑使用“复合字面量”和“指定初始化器”:*dst = (struct mystruct) { .member1 = value1, .member2 = value2, … };
。 - Jonathan Lefflerstruct
需要是const
,你可以创建一些包含不同初始化列表的宏,然后在它们之间使用#ifdef
。虽然不太美观,但没有其他选择。 - Lundin