Nested IF statements or multiple conditions?

In summary: Once you're confident you have the logic working, then optimize for speed. Even then, only optimize the parts that are causing problems.
  • #1
sk1105
88
12
Currently in my C++ program I have something like
Code:
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:
if (A){
  do thing 1;
  if (B){
    do thing 2;
    if (C){
      do thing 3;
    }
  }
}
Or would it make no/negligible difference?
 
Technology news on Phys.org
  • #2
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.
 
  • Like
Likes Silicon Waffle
  • #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.
 
  • Like
Likes Silicon Waffle
  • #4
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.
 
  • #5
  • #6
Borg said:
I assume that C++ has if-else if-else conditions?
Yes, same as C.
 
  • #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.
 
  • Like
Likes Rx7man and Samy_A
  • #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!
 
  • #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();
       }
   }
}
 
  • #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:
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)
 
  • #11
For such a lengthy if - then - else if I prefer converting the tests to an integer. For example:
Code:
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:
  • Like
Likes Rx7man
  • #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.
 

Related to Nested IF statements or multiple conditions?

1. What is the purpose of using nested IF statements?

Nested IF statements allow for more complex decision-making by allowing multiple conditions to be evaluated within a single statement. This can be useful for creating conditional logic in programs or formulas.

2. How many conditions can be included in a nested IF statement?

There is no limit to the number of conditions that can be included in a nested IF statement. However, it is important to keep the statement organized and easy to read for better understanding and debugging.

3. Can I use logical operators in nested IF statements?

Yes, logical operators such as AND, OR, and NOT can be used in nested IF statements to combine multiple conditions. This allows for more complex and specific conditions to be evaluated.

4. What happens if none of the conditions in a nested IF statement are met?

If none of the conditions in a nested IF statement are met, the statement will move on to the next line of code or the default value will be returned. It is important to include a final, catch-all condition to account for all possible scenarios.

5. Is there an alternative to using nested IF statements for multiple conditions?

Yes, there are other methods for evaluating multiple conditions such as using the SWITCH statement or creating a lookup table. These alternatives may be more efficient or easier to read depending on the specific situation.

Similar threads

  • Programming and Computer Science
Replies
12
Views
2K
  • Programming and Computer Science
Replies
16
Views
1K
  • Programming and Computer Science
Replies
5
Views
1K
  • DIY Projects
Replies
6
Views
612
  • Programming and Computer Science
Replies
7
Views
722
  • Programming and Computer Science
Replies
10
Views
1K
  • Programming and Computer Science
Replies
2
Views
2K
Replies
6
Views
1K
  • Programming and Computer Science
Replies
6
Views
1K
  • Programming and Computer Science
Replies
2
Views
1K
Back
Top