Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Nested IF statements or multiple conditions?

Tags:
  1. Jan 25, 2016 #1
    Currently in my C++ program I have something like
    Code (C):

    if (A){
      do thing 1;
    }
    if (A && B){
      do things 1 and 2;
    }
    if (A && B && C){
      do things 1 and 2 and 3;
    }
     
    and so on. Unfortunately this has to be done for a very large sample and it takes quite a long time. I was just wondering if it's more efficient to use nested if statements i.e.
    Code (C):

    if (A){
      do thing 1;
      if (B){
        do thing 2;
        if (C){
          do thing 3;
        }
      }
    }
     
    Or would it make no/negligible difference?
     
  2. jcsd
  3. Jan 25, 2016 #2

    Borg

    User Avatar
    Science Advisor
    Gold Member

    I assume that C++ has if-else if-else conditions? That would be more efficient because, once one is found, it won't check the others.
     
  4. Jan 25, 2016 #3
    It depends on what A, B, and C are. If it's doing complicated deep checking of containers or something, then yes, it would be more efficient to just check once and nest them. If it's simple integer comparison or something, then either way would be fine since those operations take nanoseconds.

    EDIT: As borg said, use else if too.
     
  5. Jan 25, 2016 #4

    QuantumQuest

    User Avatar
    Gold Member

    This is pretty much a very usual concern, in many programming languages. Rule of thumb, is to design program so that it is not driven through unnecessary checks i.e checking twice or more the same things, if - and you usually can, do it more efficiently. So, you have effectively to minimize logical conditions and a good way to do that, is to sketch your program as pseudocode and see what must be checked and where. You have to follow the shortest path in this regard and then proceed onto implementation. If separate if's don't do the trick, you can try rethinking logical tests/ conditions. If they can't be reduced, try nested if's. In many cases using a switch statement instead of ifs works well, but it has its limitations too. The difference in efficiency and running time could be big, if you have many conditionals and many data to process.
     
  6. Jan 25, 2016 #5
    Learning the most effective way to do logic is key to writing good code. You'll need to know all of the boolean algebra identities, this is a good place to start: https://en.wikipedia.org/wiki/Boolean_algebra
     
  7. Jan 25, 2016 #6

    Mark44

    Staff: Mentor

    Yes, same as C.
     
  8. Jan 25, 2016 #7
    My advice is to get it to work first and worry about efficiency later. IMO one of the most common programming faults is worrying too much about efficiency when the main issue is really correctness.

    Just write it in the simplest possible way so that it is "obviously" correct. If it isn't fast enough, then use a profiler to find out where the holdup is. Usually it is in just a few lines of code that are executed over and over.

    To this end the first style is better. What if the body of the if statement has a side effect on A? It might. Even if it doesn't, someone may add one later.
     
  9. Jan 27, 2016 #8
    Thanks everyone for the useful responses. What I want the program to do doesn't really lend itself to 'else if', but I tried nesting the statements and it yielded a noticeable speed improvement since the conditions are quite complex and the program no longer needs to check condition A three times and condition B twice etc (that seems like it should have been obvious now!).

    Thanks again!
     
  10. Jan 28, 2016 #9
    Evaluation of an if-condition in C++ takes place from the left of the logical operator in use. The original code snip can thus be expanded into something like this,
    PHP:
    if(A)
    {
       OnA();
       if (B)
       {
           OnAB();
           if(C)
           {
              OnABC();
           }
       }
    }  
     
  11. Feb 4, 2016 #10
    Most of what engineers spend their time doing is rearranging code to minimize calls. Figuring out what the software is supposed to do is easy, getting it right can take some time. Make sure that you know all of these boolean identities.

    Code (Text):
    x | F = x
    x & F = F
    x | T = T
    x & T = x
    x | x = x
    x & x = x
    x & !x = F
    x | !x = T
    !!x = x
    x | (y | z) = (x | y) | z
    x & (y & z) = (x & y) & z
    x | y = y | x
    x & y = y & x
    x & (x | y) = x
    x | (x & y) = x
    x | (y & z) = (x | y) & (x | z)
    !x & !y = !(x | y)
    !x | !y = !(x & y)
    x & (y | z) = (x & y) | (x & z)
     
  12. Feb 13, 2016 #11

    Svein

    User Avatar
    Science Advisor

    For such a lengthy if - then - else if I prefer converting the tests to an integer. For example:
    Code (C):
    int swvar;
    swvar = A ? 1 : 0;
    swvar += (B ? 2 : 0);
    swvar += (C ? 4 : 0)

    switch (swvar) {
      case 0: // Not A and Not B and Not C
            {  };
      case 1: // A and Not B and Not C
           { };
    ......
        };
     
    Last edited: Feb 14, 2016
  13. Feb 13, 2016 #12
    Svein makes a good point.. if you can set the bits of an integer as flags at the beginning of your function, you can check for a whole set of condition with only one integer comparison per comparison, rather than a whole bunch of boolean checks for each condition.

    I recently wrote a relatively intricate Arduino program to control an automotive turbocharger.. it's 2000 lines of code so far. I'm kinda having a friendly competition with someone else on who's system works better.. he's spent hundreds of hours and 'brain cycles' to make the program as fast as possible, using boolean algebra and only integer numbers.. I chose to use nearly all floating point numbers which take far more time to compute. The Arduino needs to 'update' the position of the turbocharger about every 10ms, but can reuse an old value a couple times.. a new position is required about every 50-100ms to prevent excessively large steps.
    The point is, despite my version is slower, it still gets everything done in within the time needed. For some applications, particularly deeply recursive ones with a lot of data, you really do need to concentrate on speed, especially the order at which it slows down.. Looking at optimized sorting algorithms can give you ideas on how you can optimize.

    Get the logic working and tested first, in the most readable manner possible.. I can't stress that enough.. unless you like trying to debug complex statements because they were optimized.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook