Nested If statements..

1
2
3
4
5
6
7
8
if...
   if...
      if...
         if...
         }
      }
   }
}


is it a good programming practice? because it looks like that this practice results to an effecient program..
No, it isn't when it can be avoided.

because it looks like that this practice results to an effecient program

?
I am new to it and have used if...else to make my programs so I learn. Remember to inlcude the else's in your statements. Sometimes using switch can help keep the code short.
if(condition1 && condition2)
Use that for having multiple conditions, you can have a slew of ways to set it up, to encompass any way multiple conditions should be met. This should compile to the same (or close to the same, at any rate, comparable efficiency) to what you have. The compiler should test the conditions from left to right, and as soon as it finds one that is not met, skip the following block.


The only time you should use something close to what you have there is:
1
2
3
4
5
6
7
8
if(condition1)
{
   doThis();
   if(condition2)
   {
       doThat();
   }
}
So that you only doThat(); if condition1 and condition2 are met, but you will still do doThis(); if only condition1 is met.

Something else that vaguely resembles what you have there is a nested if else block


edit: A complete example to show how && works:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

bool foo()
{

    std::cout << "foo";
    return true;
}

bool bar()
{
    std::cout << "bar";
    return false;
}

int main()
{
    std::cout << "false && foo()\n";
    if(false && foo());
    std::cout << "\nbar() && false\n";
    if(bar() && false);
    std::cout << "\nfoo() && bar()\n";
    if(foo() && bar());
    std::cout << "\nbar() && foo()\n";
    if(bar() && foo());
    return 0;
}
You can see any part where the first half of the conditional is false, the second half never even enters the function, as evidenced by no cout statement.
Last edited on
Topic archived. No new replies allowed.