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

Pages: 123
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.
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.
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.
Veltas wrote:
And as before equivalent goto code appears beyond what one would normally program.

What do you mean?
@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
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.
Oh, thanks for clarifying.
Topic archived. No new replies allowed.
Pages: 123