What is the " : 1" part doing in following code?
code:
struct trace_key {
const char * const key;
int fd;
unsigned int initialized : 1;
unsigned int need_close : 1;
};
What is the " : 1" part doing in following code?
code:
struct trace_key {
const char * const key;
int fd;
unsigned int initialized : 1;
unsigned int need_close : 1;
};
It is a bit field in C.
You probably don't want to use them much these days (since accessing bit fields is costly, and the memory gain is often negligible, unless you have dozen of millions of struct trace_key
in memory). In your case you'll better code:
struct trace_key {
const char * const key;
int fd;
bool initialized;
bool need_close;
};
after having added #include <stdbool.h>
(assuming C99 or better)
BTW, on my machine the sizeof(struct trace_key)
is the same with bit fields or with bool
in that particular case (since the struct trace_key
has to be word-aligned, and the end padding is larger than a bool
)