switch verses if/else if

Go To Last Post
6 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello gcc gurus!

Take a look at these two statements. They work in the same manner, but do they complie to the same code? The if statement have to evaluate every row until the correct a is found. But how does the switch work? Can it jump to the correct row directly, or does it have to evalute every row as well?

if (a==0) 
else if (a==1)
else if (a==2)
...

switch (a)
case (1)
case (2)
...

Best regards
Björn

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

> but do they complie to the same code?

Why don't you simply look at the generated code?

For simple situations, they usually compile to the same,
for large switch statements, the compiler might use a
jump table which it IMHO never tries for if/else statements.

Jörg Wunsch

Please don't send me PMs, use email if you want to approach me personally.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

dl8dtl wrote:
>
Why don't you simply look at the generated code?

Since I got all these GCC experts here and I'm not that good at assembler. :-D What happens inside the complier is really intresting.

Yes, my switch/case is HUGE. So hope it has created a jump table. Can you force it to this in some way by using good coding?

/Björn

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Are the 'a' switch values contiguous (1,2,3,4,5 - though not necessarily in that order) or are they disparate (1, 37, 89, 541, 2236)?

If the former then the compiler can probably use a jump table as it just takes 'a' and uses it to index into a jump table. It's more complicated for it to do that with the latter kind of switch values.

'Course, if the former, you could always code it yourself with a table of function pointers and call through the 'a'th entry

Cliff

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Smart idea Cliff. I'll see what I can do about it.

The real thing is a large state (switch) machine for handling a Gprs modem. Depending on the reply from the modem, different states are run. By using a statemachine, I can break and do other stuff as well.

/Björn

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Assuming that the contents of each case: are generally just a function call then the function pointer table can make for a "neater" solution but it can be less obvious to the maintainer as to what's going on.

Cliff