Which is better of the two: if-elif-else or if-else

16,751

Solution 1

I think without optimization first method should be faster.

Since in 1st method you check a once and then its b or c. if b is false then there are 3 checks(comparisons).

But in the second you check a twice if b is false(once if b is true). There will be 4 checks if b is false. but the compiler will probably optimize both to be the same.

Solution 2

obsolete due to question changes

that may not be the same since the if(b) block may change the a.

If all variables in the conditions are constant then the compiler may output the same code to avoid the additional and operation of the second variant.

The additional & is also the reason why i would prefer the first variant.

Solution 3

In my coding experience, it depends on the content of the dots. If just a single or few lines of code, I prefer the 2nd. However, if there're more, I'll use 1st block.

Share:
16,751

Related videos on Youtube

Harshdeep
Author by

Harshdeep

A Software Engg by profession. Coding excites me and I wanna know it all :) SOreadytohelp

Updated on June 04, 2022

Comments

  • Harshdeep
    Harshdeep almost 2 years

    This is not a homework question, this question is a result of just another discussion with my friend.

    I searched a lot but could not find any reliable source which establishes the answer with proper reasoning so here I am at the mecca of programmers.

    Which of the following two ways of coding is better:

    if(a)
    {
        if(b)
        ....
        else if(c)
        ....
    }
    

    or

    if(a && b)
    ...
    else if(a && c)
    ...
    

    I searched and found http://en.wikipedia.org/wiki/Cyclomatic_complexity to be useful but still could not make out final choice.

    Please provide relevant reasoning as well.

    Cheers!

    • viral
      viral almost 11 years
      By performance point of view; You will hardly get any significant performance improvement from using any of them over the other one. IMHO, It's just a readability thing, you should care about. Nothing else.
    • vlad_tepesch
      vlad_tepesch almost 11 years
      please replace the '&' by '&&', or did you really mean '&'? you also may add a tag about the used programming lanuage
    • Harshdeep
      Harshdeep almost 11 years
      @vlad_tepesch changed the question abit, if you could please take a look again.
  • vlad_tepesch
    vlad_tepesch almost 11 years
    he adapted the question, my answer is obsolete now
  • Bernhard Barker
    Bernhard Barker almost 11 years
    I think (assuming a is a boolean, not a function) that this is a perfect example of a micro-optimization, most likely giving no noticeable performance improvement for any non-trivial program. It's more about the coding-style.