我有一些代碼,看起來像這樣:如何根據條件簡潔地分配給結構體的成員?
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 =條件?5:7;'但是考慮哪一個選項使讀者更加明白髮生了什麼以及爲什麼。 –
考慮在'if'的每個分支中使用'compound literals'和'指定初始值設定項':'* dst =(struct mystruct){.member1 = value1,.member2 = value2,...};'。 –
如果'struct'需要是'const',你可以創建一些包含不同初始化列表的宏,然後在它們之間加上'#ifdef'。不漂亮,但沒有其他選擇。 – Lundin