I am new to C, and am having some fun playing around with bitwise operations. What I am doing seems to work, I am just wondering if it is considered good style.
Alright so let’s say my program has 3 command-line options, -a, -b, and -c. Previously I would have had 3 ints act as booleans, say aFlag, bFlag, and cFlag. Then when I call my processOpts( int *aFlag, int *bFlag, int *cFlag) function, I would pass &aFlag, &bFlag, and &cFlag as arguments, and set them like *aFlag = 1.
Here’s my new approach: have 1 int *options to represent all of the options, and treat it like an array of booleans. So to set them in the function:
case 'a':
*options |= 1;
break;
case 'b':
*options |= 2;
break;
case 'c':
*options |= 4;
break;
Then, back in main (or wherever), when I want to test to see if an option is chosen:
if ( *options & 1 )
// Option 'a' selected
if ( *options & 2 )
// Option 'b' selected
if ( *options & 4 )
// Option 'c' selected
My question is: which method is considered better style? The first way could be more clear and less error-prone, whereas the second would probably make for easier refactoring (no need to change function prototype, as it’s just one int).
Or, is there an even better way to do this? :D
EDIT: added breaks per Mat’s suggestion.
Thanks for all the responses, I am quite impressed with this community and its willingness to help everybody learn—you guys rock!
Using a single variable to represent a set of boolean flags works well if they are related. In general, I’d avoid doing this if the flags were not related. However in your case where the 3 flags relate to the program and how it runs, I’d say this is a good use.
As far as the implementation goes, rather than using hard coded constant values for your flags, you should define macros or an enum to represent the flags. That way it is clear that you are setting (or unsetting) which flag. Though it’s probably not necessary to use pointers here as you have in your code.
e.g.,