title: Optimize nested if statements within a loop in C/C++ with GCC
body: <p>I am testing various optimizations in C/C++ using the GCC compiler. I currently have a loop with multiple nested if statements. The conditions are computed at the beginning of the execution of the program. It looks somewhat like this:</p>
  
  <pre><code>bool conditionA = getA();
  bool conditionB = getB();
  bool conditionC = getC();
  //Etc.
  
  startTiming();
  
  do {
      if(conditionA) {
          doATrueStuff();
          if(conditionB) {
              //Etc.
          } else {
              //Etc.
          }
      } else {
          doAFalseStuff();
          if(conditionB) {
              //Etc.
          } else {
              //Etc.
          }
      }
  } while (testCondition());
  
  endTiming();
  </code></pre>
  
  <p>Where <code>doATrueStuff()</code> is an inline function that does some simple numerical computation so there is no overhead in calling it.</p>
  
  <p>Unfortunately, the conditions cannot be defined beforehand, they have to be computed during runtime. We can't even reliably predict the chance of them being true or wrong. <code>getA()</code> might as well be <code>rand()%2</code>. But once computed, their value never changes.</p>
  
  <p>There are two solutions I've thought of, one being global function pointers that are used to call the appropriate function within the loop, like this:</p>
  
  <pre><code>void (*ptrA)(void);
  //Etc.
  
  int main(int argc, char **argv) {
      //...
      if (conditionA) {
          ptrA=&amp;aTrueFunc;
      } else {
          ptrA=&amp;aFalseFunc;
      }
      //...
      do {
          (*ptrA)();
      } while (testCondition());
      //...
  }
  </code></pre>
  
  <p>That way I can eliminate all branches from the loop, however then I will have the overhead of multiple function calls slowing me down.</p>
  
  <p>Or I could simply have a different loop for each combination of conditions, something like this:</p>
  
  <pre><code>if(conditionA) {
      if(conditionB) {
          do {
              //Do A == true B == true stuff
          } while (testCondition());
      } else {
          do {
              //Do A == true B == false stuff
          } while (testCondition());
      }
  } else {
      //Etc.
  }
  </code></pre>
  
  <p>However that is a lot less elegant and gets impossible for one to do so efficiently once one starts having too many conditions, since for X conditions one needs to write 2^X loops.</p>
  
  <p>Is there a more elegant/faster way to optimize this?</p>
  
  <p>Is there even any point in this or will the compiler somehow understand that the condition doesn't change during the loop and optimize it itself?</p>
  
  <p>And out of curiosity, is there another programming language that would make writing such code easier/possible? Or would that only be possible by using assembly to change the instructions of the program once its loaded into memory?</p>