![](/img/trans.png)
[英]C How can I acces struct members of a struct that is part of a struct array in another struct?
[英]How can I concisely assign to the members of a struct depending on a condition?
我有一些看起来像这样的代码:
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中处理这种情况的正确方法是什么?
只需编写初始化成员的函数,或者如果您需要(基于意见),请使用MACRO。
顺便说一句, 我个人会这样做:
void mystruct_init( struct mystruct* dst, int const condition )
{
if ( condition )
init_first_way(..);
else
init_second_way(..);
}
或者只使用三元运算符。 请记住,您关心可读性并始终牢记:
简单是一种美德!
我真的认为在这个阶段担心优化将成为不成熟优化的受害者 ,因为我怀疑它将成为瓶颈。
一般来说,如果你想优化你的代码,分析你的代码(当它运行优化标志时,许多人不知道这一点,我就是其中之一: vs2015上stl列表的性能不佳,同时删除包含迭代器到自己的节点在列表中的位置 ),找到瓶颈并尝试优化该瓶颈。
我不认为这里有任何明确的规则。 对我来说,这取决于作者的品味。
两个明显的方法是:
// 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;
// ...
请不要担心一个函数调用开销。
我同意已发布的答案(@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.