簡體   English   中英

如何根據條件簡明地分配給結構的成員?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM