如何根据条件简洁地分配给结构体的成员?
我有一些代码,看起来像这样:如何根据条件简洁地分配给结构体的成员?
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来处理这种情况下的正确方法?
回答:
只写初始化一个成员函数,或者如果你想(意见为主),使用宏。
顺便说一句,我会亲自做这样的:
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),找到瓶颈,并尝试优化瓶颈。
回答:
我不认为这里有任何明确的规则。对我而言,这取决于作者的口味。
两个显而易见的方法是:
// 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; 
} 
以上是 如何根据条件简洁地分配给结构体的成员? 的全部内容, 来源链接: utcz.com/qa/265077.html

