Categories
c programming tips and tricks

Know when if-else becomes switch-case

Many C programmers are big fans of the if-else decision tree, but they generally avoid stacking up multiple if statements. It usually means that the programming logic is flawed. For example:

if(something)
    ;
else if(something_else)
    ;
else(finally)
    ;

This structure is okay, and it’s often necessary to deal with a 3-part decision. But the following structure, which has been built by many budding C programmers, probably isn’t the best way to code a decision tree:

if(something)
    ;
else if(something_else_1)
    ;
else if(something_else_2)
    ;
else if(something_else_3)
    ;
else if(something_else_4)
    ;
else(finally)
    ;

Generally speaking, anytime you have that many else-if statements, you probably need to employ the switch-case structure instead. In fact this example is probably what inspired the switch-case structure in the first place.

Leave a Reply

Your email address will not be published. Required fields are marked *