Search code examples
c++if-statementnested-loops

How to make a deep nested part of code be toggled without making 2 versions of it


I have the following structure of code:

for
 for
  for
   for
    {
    things
    if(condition1||condition2)
    }

And basically that "if" checks 2 variables that depends of every loop before it, but only have to be checked if the user said so at the beginning of the program, otherwise that "if" is pointless.

I could use if(boolean&&(condition1||condition2)) which would work great except for the fact that it would be checked for every single iteration of all the loops.

So my question is: Is there a way to get C++ to disable that "if" completely (without checking a condition every loop) if the user said so, without repeating itself with and without the if??? Like, for example:

if(boolean)
 {
  all the fors
    things
    if(conditio1||condition2)
 }
else
 {
  all the fors
    things
 }

This works fine but if I have to make any change in the future, I would have to write it 2 times with the possibility of forgetting about the second time or making mistakes. And I also have other 3 parts of code with the same issue, so the code would get really long.

Edit: Some of you think we are talking of insignificant numbers of iterations, but that "if" would have to be checked at least 10.8 millions times by the end of each complete program. And as I said, I have (now 2) more parts of code with the same issue, so quite some time could have been saved. Too bad the solution of if constexpr used C++17


Solution

  • You can write your code in a function like this

    template<bool Boolean>
    void code(/* parameters */)
    {
      for // ...
        for // ...
          // all the fors ...
          {
             // things 
             if constexpr (Boolean)  // compile time branch
             {
                if(condition1 || condition2)
                   // ...
             }
          }
    }
    

    The if constexpr will only be compiled when the Boolean is true. So at the call site you can do

    bool boolean = /* some run-time initialization */
    if (boolean)
      code<true>(/* arguments */);
    else 
      code<false>(/* arguments */);
    

    Note that this is not something you should do for the sake of performance, unless you've measured and profiled the code to see if it's a bottleneck. Once you've done that, you can use the above technique.


    If you're not yet using C++17, the entire if constexpr block can be replaced by

    work<Boolean>(/* arguments */);
    

    where work is a function template that's specialized to only do work in the true case:

    template<bool>
    void work(/* parameters */) {}  
    
    template<>
    void work<true>(/* parameters */) 
    {
      if(condition1 || condition2)
         // ...
    }