I saw this line of code today and had no idea what it does.
typedef enum { SomeOptionKeys = 1 << 0 // ? } SomeOption; Some usage or example would be helpful. Thanks!
It looks like it defines an enumerated type that is supposed to contain a set of flags. You'd expect to see more of them defined, like this:
typedef enum { FirstOption = 1 << 0, SecondOption = 1 << 1, ThirdOption = 1 << 2 } SomeOption; Since they are defined as powers of two, each value corresponds to a single bit in an integer variable. Thus, you can use the bitwise operators to combine them and to test if they are set. This is a common pattern in C code.
You could write code like this that combines them:
SomeOption myOptions = FirstOption | ThirdOption; And you could check which options are set like this:
if (myOptions & ThirdOption) { ... } The value of SomeOptionKeys is one, this is a useful representation when working with flags:
typedef enum { flag1 = 1 << 0, // binary 00000000000000000000000000000001 flag2 = 1 << 1, // binary 00000000000000000000000000000010 flag3 = 1 << 2, // binary 00000000000000000000000000000100 flag4 = 1 << 3, // binary 00000000000000000000000000001000 flag5 = 1 << 4, // binary 00000000000000000000000000010000 // ... } SomeOption; Whit way each flag has only one bit set, and they could be represented in a bitmap.
Edit:
Although, I have to say, that I might be missing something, but it seems redundent to me to use enums for that. Since you lose any advantage of enums in this configuration, you may as well use #define:
#define flag1 (1<<0) #define flag2 (1<<1) #define flag3 (1<<2) #define flag4 (1<<3) #define flag5 (1<<4) << is the left shift operator. In general, this is used when you want your enums to mask a single bit. In this case, the shift doesn't actually do anything since it's 0, but you might see it pop up in more complex cases.
An example might look like:
typedef enum { OptionKeyA = 1<<0, OptionKeyB = 1<<1, OptionKeyC = 1<<2, } OptionKeys; Then if you had some function that took an option key, you could use the enum as a bitmask to check if an option is set.
int ASet( OptionKeys x){ return (x & OptionKeyA); } Or if you had a flag bitmap and wanted to set one option:
myflags | OptionKeyB
1 << 0 == 1, I don't see the point. Is this the completeenum? These constructs are often used with|.fst = 1 << 0, sec = 1 << 1, thr = 1 << 2just for the sake of completeness (in columns, of course, not in this one-line).