Nested if() vs &&

A lot of sketches I see uses nested if statements

if (X==Y)
{
  if(A==B)
  {
    // do stuff
  }
}

Sometimes this is obviously necessary, but often it seems to make as much sense to use && (and I find it far easier to read):

if ((X==Y) && (A==B))
{
  // do stuff
}

If the latter works in a particular situation, are there reasons not to use it?

Just style. They will both compile to the same code.

The nested ifs may be easier to debug because you can insert print statements inside each of them to discover the exact program flow. You can, of course, print the values being tested in the logical and version before they are tested, but then you have to interpret them yourself

Nested ifs can also make the intentions of the programmer clearer because of the indentation of code making code blocks more obvious

Another consideration is the length of the line of code. I prefer to be able to see an entire line of code, including comments, without scrolling sideways if possible, and that is easier using nested ifs

But, as Ray says, it is just a matter of style

Thanks. Good to know, and interesting that the compiler doesn't care. :slight_smile:

I agree about readability. A couple of times when I've ended up with long if() statements, the way I've tried to make it more readable is something like this ...

if ((X==Y)       // Comment
  && 
  (A==B))        // Comment
{
  // do stuff
}

Long if-statements are an indication that the structure of the code might not be optimal :wink:

If someone has spaghetti of if-statements, and it still does not work, then sometimes a Finite State Machine can make it work with very simple if-statements.

In C++ you get away with rolling this all into a single if statement, but the order of expression evaluation is not guaranteed in all languages/compiler implementations

if ( x != 0 ) {

    if ( y / x  > 42 ) {
        // do something
    }

}

It also helps execution time, if that matters, if you put the test that is most unlikely to return true at the start of the stack of tests. That way, when the first test returns false the others are are skipped

When you group two conditions with an && you don’t know which condition(s) was/were false if you get into the else statement.

Having two if statements gives you also opportunities for two else statements.

That would be one good reason to separate into two if when needed

All useful. Thanks.

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