Helping the compiler with assumptions while using exceptions

simendsjo simen.endsjo at pandavre.com
Mon May 30 12:49:30 PDT 2011


I'm having some problems trying to get the best of both worlds here.

void f(Class c) {
   assert(c != null);
   // use c
}

In this example, we tell the compiler that c is never able to be null. 
The compiler can use assertions like this for optimizations (not sure if 
dmd does this though).

But assert is only a debugging tool.
Say we wanted to have this check at runtime too - just in case - so we 
can fail where the problem is.

So we do this:

void f(Class c) {
   enforce(c != null);
   // use c
}

But now the compiler has no idea c will never be null later on (or does 
it...?).

We could always do this:

void f(Class c) {
   assert(c != null);
   enforce(c != null);
   // use c
}

But this is overly verbose.

Or is this not a problem at all? E.g. Use enforce for runtime checks - 
the compiler understands them/won't use asserts for optimizations anyway?


More information about the Digitalmars-d-learn mailing list