If and if not vs if and else

I've found numerous articles on else if but can't find a definitive answer on this.

On reviewing some of my (novice) code, I've found instances of this:

if (i==0) {
    // stuff
}
if (i!=0) {
    // otherStuff
}

I can see it is probably more correct to do this:

if (i==0) {
    // stuff
}
else {
    // otherStuff
}

but is there anything inherantly problematic about the first example?

Both will work fine. The 2nd example is probably marginally quicker because once the 1st if is true the 2nd statement doesn't need to be evaluated. Having said that, the complier is pretty smart and may well optimise the code to the same for both.

1 Like

No. Sometime ppl will criticize the former as noobish, but it can be useful to reiterate the test for clarity, if the blocks are big.

But… if i were to be modified in the first if statement, the code might do both blocks, what you might not have meant and could be a hard thing to spot so watch out for that.

Sometimes I

  if (whatever) {

  }
  else {   // not whatever

  }

put the redundant test in a comment for clarity.

a7

i could change value between the tests, which is impossible with the else version.

1 Like

For example, this will always toggle 'i' between 0 and 1:

if (i == 0) 
  i = 1;
else
  i = 0;

But this will always set 'i' to zero:

if (i == 0) 
  i = 1;
if (i != 0) 
  i = 0;
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.