Bit Flags

closed account (zb0S216C)
I understand bit-flags but I don't know how to create them. So far this is the only way I know how to create a bit-flag:
1
2
3
4
struct Bit_Flags
{
    int Flag_Failed:1;  // 1-bit flag.
} Bit_Flags;


Is this preprocessor define directive the same as the one above?
 
#define FLAG_FAILED:1 


I know how to use bitset, but, I'm just exploring alternatives.
Erm, no, not really...I'm not sure what you think that define does, but at best is simply defines "FLAG_FAILED:1" and nothing else...

Btw, I'd change the int to bool, because by definition, a flag is only true or false. (Plus 1 bit can only be true or false anyway).
You could use an int (here assuming an int is 32 bits large, but that's the case on most platforms and compilers anyways):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#define FLAG1 0x01
#define FLAG2 0x02
#define FLAG3 0x04
#define FLAG4 0x08
#define FLAG5 0x10
#define FLAG6 0x20
//and so on
int flags;
// set a flag:
flags = flags | FLAG1;
//check whether a flag is set or not
if(flags & FLAG1)
//check whether multiple flags are set
if(flags & (FLAG1 | FLAG2 | FLAG3))
//set all flags at once
flags = numeric_limits<unsigned int>::max();
Last edited on
closed account (zb0S216C)
Thanks, Hanst. I was going to ask how I can test to see what flags were set, but, you already gave me an example. Thanks again, Hanst.
Topic archived. No new replies allowed.