C Options Good Style? -


I'm new to C, and playing with some fun bitwall operation. What I'm doing seems to work, I'm just thinking that this is considered a good style.

OK, so let's say that there are 3 command line options in my program, -a , -b , and -c . Before I perform 3 entities as a boolean, first called aflag , bFlag , and cFlag . Then when I call my processOpts (int * aFlag, int * bFlag, int * cFlag) function, then I'll call and eflag , and & amp; BFlag , and and cFlag , and set them as * aflag = 1 .

This is my new way: 1 int * options to represent all the options, and treat it as an array of boolean, then set them to function For:

  case 'a': * options | = 1; break; Case 'B': * Options | = 2; break; Cases 'C': * Options | = 4; break;   

Then, back to (or wherever) in main , when I want to see that an option is selected:

 < // if option 'A' is chosen (* option & amp; 1) // (option & amp; 2) // option 'B' selected (* option & amp; 4) // option ' C 'selected   

My question is: Which method is considered a better style? The first way can be more pronounced and less error prone, while the second is probably for easy refactoring (there is no need to change the function prototype because it is just a int ).

Or, is there a better way to do this? : D

Edit: Broken additions according to each suggestion

Thank you for all the responses, I am quite impressed with this community and you guys rock to learn the desire to help everyone!

To represent the work of Boolean flags use a single variable well if they are related Normally, I avoid doing this if the flags are not related, although in your case where 3 flags are related to the program and how it runs, I can say that this is a good use.

As far as the implementation goes on, you should define macros or anonymity to represent the flag, the flag instead of using the string-coded static values ​​for your code. In this way it is clear that you are setting (or discontent) flag which although it is probably not necessary to use the indicators present in your code.

For example,

  enum option {OPTION_none = 0, OPTION_a = 0x1, OPTION_b = 0x2, OPTION_c = 0x4,}; Enum Choice Process (int argc, char ** argv) {enum option option = OPTION_none; If (argc> 1) {int i; (I = 1; i & lt; argc; i ++) {if (argv [i] [0] == '-') {switch (argv [i] [1]) {case 'a': Options | = OPTION_a; break; Case 'B': Options | = OPTION_b; break; Case 'C': Options | = OPTION_c; break; }}} Return option; } Int main (int argc, char * argv []) {enum option option = processOpts (argc, argv); If (option & amp; OPTION_a) option for the option a * /} if (option & amp; OPTION_b) {/ * option for the goods b * /} if (option & amp; OPTION_c) option Do stuff for C * return 0; }    

Comments