A question about Switch Case

Guys, this is a very basic question, but still, I wonder about this. In a Switch () Case, does the processor have to check each case, or it jumps right to the correct case directly?

http://arduino.cc/en/Reference/SwitchCase

For instance:

switch (value) { case 1: .... break; case 2: .... break; case 3: .... break; case 4: .... break; case 5: .... break; }

When value is == 5, does it checks case 1, skip, case 2, skip, case 3, skip, case 4, skip, case 5, found, execute code. Or it jumps directly to case 5 like a "goto 5" call?

Thanks. Best Regards, WilliamK

It checks each one in turn, and jumps out of the switch block when it does 'break'.

So, the longer number of cases, the longer it takes to process, right?

Wk

Yes, but you are probably only looking at 1 microsecond per comparison.

Put the most likely answer at the top.

It checks each one in turn

Not necessarily - depending on the size of the switch and the values, the optimiser may be able to use a lookup.

If it becomes a real problem you’re better off with a jump table. That’s not normally worth the effort but can make for better and faster code.


Rob

If it becomes a real problem you're better off with a jump table

That's what optimisers are there for.

But those the arduino GCC compiler optimize by itself, or I need to add something? And what's a Jump Table? :pos1 and goto pos1?

Wk

Sorry William I shouldn't have muddied the waters, for what you seem to be doing the compiler will do just fine.

Jump tables are good for state machines and command handlers etc. They normally have an array of function adresses, and you "jump to" a specific function according to a value.


Rob