www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - final switch usage

reply #ponce <aliloko gmail.com> writes:
For the low-level programmer, sometimes you must use switch because virtual
functions are more expensive (cache usage...) and pointers to functions too.

The problem is that even if the optimizer turn the switch into a jump-table, it
has generally no clue about whether the value will be in the right range. Only
static analysis could do that and in C/C++ well...

So in C++ production code I'm currently forced to use something like this :

#pragma_assert(x >= 0)
#pragma_assert(x <= MAX)

  case 0: doSomething0(); break;
  case 1: doSomething1(); break;


  case MAX: doSomethingMAX(); break;

to make the optimizer know that i'm in the good range and drop the runtime
check (such conditionnals breaks pipeline).

My proposition is that final switch does a runtime check and eventually throw
an exception in debug mode, but does not check anything in release mode. It
would be consistent with how ArrayBoundsException works. 

It may seems a stupid request since I don't know how final switch works

But my feeling is that it would make the fastest possible dynamic dispatch,
without loosing reliability. This could be very valuable for people interested
in performance.
Aug 06 2009
next sibling parent ponce <aliloko gmail.com> writes:
In fact final switch can be an improved computed GOTO :)
Aug 06 2009
prev sibling parent Walter Bright <newshound1 digitalmars.com> writes:
You're right that final switch could drop the range check. You should 
post this as an enhancement request to bugzilla!
Aug 07 2009