switch vs if

Hi Guys,

I have a general programming question regarding which is a better implementation, switch or if. For example, which of the following is a better implementation, especially at kernel level and driver module level:-

Scenario 1 –

switch(key)
case A:
dosomething();
break;
case B:
dosomething();
break;
}

Scenario 2 –

if (key == A)
doSomething();
if (key == B)
doSomething();

Also, is nested switch statements a good practise? I can implement separate functions to avoid nested switch statements but worried about function calling overhead costs.

Thank you,
KT

Don’t worry about that, compiler are so good these day that they will figure out the best assembly code for you. In fact compiler may even decide to inline some of your own function.

Actually code generated by compiler is so unpredictable ( depends on optimizer flag, cpu type, etc), even the code that is generated could be fast on P4, but not as fast as possible on P3, or AMD.

Just make the code easy to read and maintain. You are waisting your time thinking so low lever ( unless you’d be working with 8bit CPU running at 1Mhz)

Thanks Mario.

-KT

By the way under QNX there is no such thing as “kernel level”, well not 100% true, i guess interrupt service routine can be consider kernel level.

And the is no such thing as driver module level, although there are frameworks for various type of driver they are not leveled as they don’t have access to more resources then any other applications.