If Goto is "considered harmful," then so can...

Pages: 123
Aug 20, 2012 at 9:14pm
chrisname wrote:
I don't really see how a goto can be optimised since non-conditional jumps are about as quick as they can get.


Please excuse me, I mean to say that switch statements can be easily optimised but the result is something that is very ugly in goto statements, far worse than the switch statement indeed!

It is to do with splitting up the comparisons into groups rather than individual cases. e.g. half the switch's options are positive and half negative, then the first check is for the sign, then whether or not one of the positives/negatives or the other; 2 comparisons at most, rather than 4 which is the simple examination that you would have had with just gotos in a simple form.
Aug 20, 2012 at 9:26pm
Switches with more than a certain number of cases (I've read 5, but I'm sure it varies by compiler) are optimised into jump tables, so no comparisons need to happen. All the compiler has to do is generate an array of addresses with one address for each case label, and then just use the value of the switch expression as the index into the array.
Aug 20, 2012 at 9:30pm
Then look at the comparisons and they scale in the same way.

And as before equivalent goto code appears beyond what one would normally program.
Aug 20, 2012 at 10:25pm
Veltas wrote:
And as before equivalent goto code appears beyond what one would normally program.

What do you mean?
Aug 23, 2012 at 2:10am
@chrisname
Switches with more than a certain number of cases (I've read 5, but I'm sure it varies by compiler) are optimised into jump tables, so no comparisons need to happen. All the compiler has to do is generate an array of addresses with one address for each case label, and then just use the value of the switch expression as the index into the array.


Oh. I didn't know that until now, so I'm very thankful you included it in your response; a fact which is quite valuable, though rarely shared.
Last edited on Aug 23, 2012 at 2:11am
Aug 23, 2012 at 3:34am
The cases also have to meet certain additional requirements. A switch like
1
2
3
4
5
6
7
8
9
10
11
12
switch (/*...*/){
    case 1:
        //...
    case 50:
        //...
    case 1000:
        //...
    case 1000000:
        //...
    case 5000000:
        //...
}
will not get optimized.
In general, it's safer to assume that a switch will not be optimized.
Aug 24, 2012 at 7:20pm
Oh, thanks for clarifying.
Topic archived. No new replies allowed.
Pages: 123