2014-11-25 53 views
0

什麼是「:1」部分在下面的代碼中做什麼?c - struct - 額外的「:1」在做什麼?

代碼:

struct trace_key { 
     const char * const key; 
     int fd; 
     unsigned int initialized : 1; 
     unsigned int need_close : 1; 
}; 
+10

這意味着您應該查閱文檔。 – leppie 2014-11-25 09:13:13

+5

請參閱C編程中的'Bitfields' – 2014-11-25 09:13:55

+0

@Santosh謝謝。 – 2014-11-25 09:14:41

回答

1

它是一個bit field in C

你可能現在不想使用它們(因爲訪問位域代價高昂,除非你在內存中有數十萬個struct trace_key),內存增益通常可以忽略不計。在你的情況,你會更好的代碼:

struct trace_key { 
    const char * const key; 
    int fd; 
    bool initialized; 
    bool need_close; 
}; 

已增加#include <stdbool.h>(假設C99或更好)

順便說一句,我的機器sizeof(struct trace_key)後在特定的情況下,與位域相同或bool (因爲struct trace_key必須是字對齊的,並且結尾填充大於bool

+0

謝謝,我會谷歌有關。 – 2014-11-25 09:16:08

+0

您還應該進行實驗和基準測試。 – 2014-11-25 09:22:21

+1

當然,我從git源碼trace.h中看到了代碼,試圖通過視圖源代碼學習c編程,謝謝。 – 2014-11-25 09:24:17