title: Writing a variadic macro which sets specific bits in an integer (bit-mask)
body: <p>I'm trying to write a macro which simplifies setting multiple bits in an integer. This commonly occurs in microcontroller code when initializing configuration registers. For example, one might configure an 8-bit timer by setting 3 bits in the register <code>TCCR0A</code> like this:</p>
  
  <pre><code>// WGM01, WGM00 and COM0A1 are constants between 0 and 7
  // There are hundreds of these constants defined in avr-libc
  TCCR0A |= (1&lt;&lt;WGM01) | (1&lt;&lt;WGM00) | (1&lt;&lt;COM0A1);
  
  // Another way to write this:
  #define _BV(bit) (1 &lt;&lt; (bit)) // &lt;-- defined in avr-libc
  TCCR0A |= _BV(WGM01) | _BV(WGM00) | _BV(COM0A1);
  </code></pre>
  
  <p>However, I'd find it a lot easier to write something like this:</p>
  
  <pre><code>TCCR0A |= BITS(WGM01, WGM00, COM0A1); // &lt;- Variable # of arguments please!
  </code></pre>
  
  <p>Since I can't imagine that nobody has thought of this yet, I searched around but found nothing which does exactly this. I wonder if this is possible at all, but I gave it a shot anyways while reading <a href="https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html" rel="nofollow">https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html</a> and <a href="https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms" rel="nofollow">https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms</a>.</p>
  
  <hr>
  
  <p>Here's what I tried so far. I imagine the solution must be recursive macro, but didn't get very far when trying to get it to expand correctly. Since all my registers are 8 bits long, 8 expansion passes should be sufficient (for a first try).</p>
  
  <pre><code>#define BITS_EVAL(...)  BITS_EVAL1(BITS_EVAL1(BITS_EVAL1(__VA_ARGS__)))
  #define BITS_EVAL1(...) BITS_EVAL2(BITS_EVAL2(BITS_EVAL2(__VA_ARGS__)))
  #define BITS_EVAL2(...) __VA_ARGS__
  
  #define BITS(bit, ...) ((1 &lt;&lt; bit) | BITS_EVAL(BITS(__VA_ARGS__)))
  </code></pre>
  
  <p>The above doesn't quite work. What it currently does is:</p>
  
  <pre><code>// BITS(2,5,7) --&gt; ((1 &lt;&lt; 2) | BITS(5, 7))
  </code></pre>
  
  <p>However, what I would like to achieve is one of these (or equivalent):</p>
  
  <pre><code>// BITS(2,5,7) --&gt; ((1 &lt;&lt; 2) | (1 &lt;&lt; 5) | (1 &lt;&lt; 7))
  // BITS(2,5,7) --&gt; ((1 &lt;&lt; 2) | ((1 &lt;&lt; 5) | ((1 &lt;&lt; 7))))
  </code></pre>
  
  <p>Can anyone help me with my quest, or tell me that it's impossible to achieve this?</p>