using else if

do you have to use
1
2
3
4
5
6
7
8

if(x == 3)
{
}

else if (x == 4)
{
}


because i always use

1
2
3
4
5
6
7
8

if(x == 3)
{
}

if (x == 4)
{
}


i never though it mattered. is it bad practice?
Last edited on
if x = 3 and the first conditional changes x to 4 then the second loop would also run.
however using else if the second loop would not run, so it's situational. Up to you, and I would not consider it "bad practise".
If x == 3, x cannot be == 4.
Without the else you perform another (useless) comparison which will waste your time.
Bazzy wrote:
Without the else you perform another (useless) comparison which will waste your time.

Is it less computation using a "if, else if" compared to 2 'if's' ? I would have thought it would be the same. However it does matter if the conditional is changing the variable: typically I would use 'else if' unless I wanted the second conditional in there to keep doing stuff manipulating the object/variable w.e
Is it less computation using a "if, else if" compared to 2 'if's' ?
You can try this program:
1
2
3
4
5
6
7
    int x = 3;
    cout << "Without else:";
    if ( cout << "\n\tx == 3", x == 3 );
    if ( cout << "\n\tx == 4", x == 4 );
    cout << "\n\nWith else:";
    if ( cout << "\n\tx == 3", x == 3 );
    else if ( cout << "\n\tx == 4", x == 4 );
You have two comparisons without else
the x == 3 and x ==4 was just an example. so general it doesnt matter
It does matter. If the first condition is met, without else the second will be evaluated anyway. You can save this evaluation by putting else
If you don't have the circumstances gcampton mentioned ( you modify the variable in the first if block and you want to check again )
you should put the else
Ah of course. I didn't get to re-read this post after I replied last time. Thanks for clarifying baz.

in the case of x = 3:
1
2
3
4
if (x==3)  // is evaluated and is true
    doSomething();
else if (x==4)  // is not evaluated due to the above being true
    doSomethingElse();

the above will only ever have 1 comparison for the first if, if true.
However the using 2 if's both are evaluated.
1
2
3
4
if (x==3)  // is evaluated and is true
    doSomething();
if (x==4) // is also evaluated and is false.
    doSomethingElse();


So unless you need to do re-evaluation you should use an else to save on the computation.
Opposite example:
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
28
int main()
{
  int n1, n2, n3, n4, n5;
  int smallest, largest;


  cout << "Input five integers: ";

  cin >> n1 >> n2 >>  n3 >> n4 >> n5;

  //find smallest
  //-------------

  smallest = n1; //assume first n is smallest and prove otherwise

  if (n2 < smallest)
    smallest = n2;

  if (n3 < smallest)
    smallest = n3;

  if (n4 < smallest)
    smallest = n4;

  if (n5 < smallest)
    smallest = n5; 
  
  ... // etc 
Last edited on
Topic archived. No new replies allowed.