我有一个struct喜欢以下内容:
struct Foo {
unsigned int id;
unsigned int flag_1 : 1;
unsigned int flag_2 : 1;
unsigned int flag_3 : 1;
// Some arbitrary number of further flags. Code is
// automatically generated and number will vary.
// Notably, it may be more than an int's worth.
int some_data;
float some_more_data;
// ...
};
Run Code Online (Sandbox Code Playgroud)
有时,我需要将所有标志重置为零,同时保留结构的其余部分。一种方法显然是将每个标志单独设置为 0,但感觉应该有一种方法可以一举完成。那可能吗?
(请注意,我愿意不使用位域,但这些代码有时会在内存受限的系统上运行,因此节省的内存非常吸引人。)
编辑:
这里有一个类似的问题:Reset all bits in ac bitfield
但是,该问题中的结构完全是位域。我不能memset在这里简单地将整个结构归零,并且不能保证涉及联合的其他答案有效,尤其是当标志的价值超过 int 时。
只需使用单独struct的标志:
struct Foo_flags {
unsigned int flag_1 : 1;
unsigned int flag_2 : 1;
unsigned int flag_3 : 1;
// ...
};
struct Foo {
unsigned int id;
struct Foo_flags flags;
int some_data;
float some_more_data;
// ...
};
Run Code Online (Sandbox Code Playgroud)
甚至更简单的嵌套struct:
struct Foo {
unsigned int id;
struct {
unsigned int flag_1 : 1;
unsigned int flag_2 : 1;
unsigned int flag_3 : 1;
// ...
} flags;
int some_data;
float some_more_data;
// ...
};
Run Code Online (Sandbox Code Playgroud)
然后,稍后在您的代码中:
struct Foo x;
// ...
x.flags.flag_1 = 1;
// ...
memset(&x.flags, 0, sizeof(x.flags));
Run Code Online (Sandbox Code Playgroud)