Note that there are some explanatory texts on larger screens.

plurals
  1. POC Options Good Style?
    primarykey
    data
    text
    <p>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.</p> <p>Alright so let's say my program has 3 command-line options, <code>-a</code>, <code>-b</code>, and <code>-c</code>. Previously I would have had 3 ints act as booleans, say <code>aFlag</code>, <code>bFlag</code>, and <code>cFlag</code>. Then when I call my <code>processOpts( int *aFlag, int *bFlag, int *cFlag)</code> function, I would pass <code>&amp;aFlag</code>, <code>&amp;bFlag</code>, and <code>&amp;cFlag</code> as arguments, and set them like <code>*aFlag = 1</code>.</p> <p>Here's my new approach: have 1 <code>int *options</code> to represent all of the options, and treat it like an array of booleans. So to set them in the function:</p> <pre><code>case 'a': *options |= 1; break; case 'b': *options |= 2; break; case 'c': *options |= 4; break; </code></pre> <p>Then, back in <code>main</code> (or wherever), when I want to test to see if an option is chosen:</p> <pre><code>if ( *options &amp; 1 ) // Option 'a' selected if ( *options &amp; 2 ) // Option 'b' selected if ( *options &amp; 4 ) // Option 'c' selected </code></pre> <p>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 <code>int</code>).</p> <p>Or, is there an even better way to do this? <code>:D</code></p> <p>EDIT: added breaks per Mat's suggestion.</p> <p>Thanks for all the responses, I am quite impressed with this community and its willingness to help everybody learn—you guys rock!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload