title: Compiler optimization of if statement in C
body: <p>I have a function like this in C (in pseudo-ish code, dropping the unimportant parts):</p>
  
  <pre><code>int func(int s, int x, int* a, int* r) {
      int i;
  
      // do some stuff
  
      for (i=0;i&lt;a_really_big_int;++i) {
          if (s) r[i] = x ^ i;
          else r[i] = x ^ a[i];
          // and maybe a couple other ways of computing r
          // that are equally fast individually
      }
  
      // do some other stuff
  
  }
  </code></pre>
  
  <p>This code gets called so much that this loop is actually a speed bottleneck in the code. I am wondering a couple things:</p>
  
  <ol>
  <li><p>Since the switch <code>s</code> is a constant in the function, will good compilers  optimize the loop so that the branch isn't slowing things down all the time?</p></li>
  <li><p>If not, what is a good way to optimize this code?</p></li>
  </ol>
  
  <p>====</p>
  
  <p>Here is an update with a fuller example:</p>
  
  <pre><code>int func(int s,
           int start,int stop,int stride,
           double *x,double *b,
           int *a,int *flips,int *signs,int i_max,
           double *c)
  {
    int i,k,st;
    for (k=start; k&lt;stop; k += stride) {
      b[k] = 0;
      for (i=0;i&lt;i_max;++i) {
  
        /* this is the code in question */
        if (s) st = k^flips[i];
        else st = a[k]^flips[i];
        /* done with code in question */
  
        b[k] += x[st] * (__builtin_popcount(st &amp; signs[i])%2 ? -c[i] : c[i]);
      }
    }
  }
  </code></pre>
  
  <hr>
  
  <p>EDIT 2:</p>
  
  <p>In case anyone is curious, I ended up refactoring the code and hoisting the whole inner for loop (with <code>i_max</code>) outside, making the <code>really_big_int</code> loop be much simpler and hopefully easy to vectorize! (and also avoiding doing a bunch of extra logic a zillion times)</p>