user6096479 user6096479 - 1 year ago 43
C Question

Definining a constant that holds all OR-ed values

My application make use of OR-ed values, like this example (pseudo):

#define OPTION_1 1
#define OPTION_2 2
#define OPTION_3 4
#define OPTION_4 8

These constants gets OR-ed in various functions in the form of integers, like that:


Sometimes i have many OPTIONS to pass on a function that i rather not. I prefer to have a option constant like that:

#define OPTION_ALL ?? <-- include all options

to hold anything and instead pass that as a default maybe.

Is this possible? I tried:

#define OPTION_ALL 8

Or is this the only solution?



It seems this is the best way:

#define OPTION_1 0
#define OPTION_2 1
#define OPTION_3 2
#define OPTION_4 4
#define OPTION_ALL (OPTION_4 * 2) - 1

It just uses the last option as input

Answer Source

Yes, But OPTION_1 cannot be 0. It should be 1 and then OPTION_ALL will be 15

#define OPTION_1      1
#define OPTION_2      2
#define OPTION_3      4
#define OPTION_4      8
#define OPTION_ALL    15

Basically what you are doing is that you are setting one bit in binary as 1 for each option. i.e.

#define OPTION_1      0b00000001
#define OPTION_2      0b00000010
#define OPTION_3      0b00000100
#define OPTION_4      0b00001000
#define OPTION_ALL    0b00001111

And you can then extend as necessary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download