title: Self-unrolling macro loop in C/C++
body: <p>I am currently working on a project, where every cycle counts. While profiling my application I discovered that the overhead of some inner loop is quite high, because they consist of just a few machine instruction. Additionally the number of iterations in these loops is known at compile time.</p>
  
  <p>So I thought instead of manually unrolling the loop with copy &amp; paste I could use macros to unroll the loop at compile time so that it can be easily modified later.</p>
  
  <p>What I image is something like this:</p>
  
  <pre><code>#define LOOP_N_TIMES(N, CODE) &lt;insert magic here&gt;
  </code></pre>
  
  <p>So that I can replace <code>for (int i = 0; i &lt; N, ++i) { do_stuff(); }</code> with:</p>
  
  <pre><code>#define INNER_LOOP_COUNT 4
  LOOP_N_TIMES(INNER_LOOP_COUNT, do_stuff();)
  </code></pre>
  
  <p>And it unrolls itself to:</p>
  
  <pre><code>do_stuff(); do_stuff(); do_stuff(); do_stuff();
  </code></pre>
  
  <p>Since the C preprocessor is still a mystery to me most of the time, I have no idea how to accomplish this, but I know it must be possible because Boost seems to have a <code>BOOST_PP_REPEAT</code> macros. Unfortunately I can't use Boost for this project.</p>