AJ wrote:
I guess that this optimisation is fair enough with -O2. If it did the same with -Os, you would be a bit disappointed, though (unfortunately I'm on a computer without GCC at the moment and am not going to install it to find out!).
Me neither.
AJ wrote:
For example, if you had values 1000000, 1000002, 1000007 etc..., perhaps it would still do the same but just add an initial offset.
If you look at that second example of solar's, you can see that is precisely what it did. The switch values went from 5 to 51. On the very first line, it subtracted the 5, and ran the sparse table from 0 to 46.
AJ wrote:
If, however, you had 0, 1001, 100002, 1000007 etc, I would hope that it wouldn't create a sparse lookup...
Obviously, it won't.
-- that was half the point of my post.
But the other half was the question: what is gcc's
fallback algorithm when it is too expensive to just make a sparse lookup table? Under this case, will it just code the switch as a nested if? That is my guess -- that there *is* no fallback algorthm. That "switch" is only efficient if you have a "tight" set of switch values. If the values are not sufficiently dense, then switch isn't any more efficient than a nested if.
Or, will it try to somehow convert the switch values to indices, and use the indices in a tight lookup table?