Helping the compiler with assumptions while using exceptions
bearophile
bearophileHUGS at lycos.com
Mon May 30 13:48:02 PDT 2011
simendsjo:
> 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).
I think currently DMD is not using this information, and probably it will keep not using it for some more time.
Note: generally asserts go into Contracts. Here it goes in the precondition of f:
void f(Class c)
in {
assert(c != null);
}
body {
// use c
}
> void f(Class c) {
> assert(c != null);
> enforce(c != null);
> // use c
> }
This is not meaningful. assert and enforce have different purposes, you don't use both of them at the same time. If f is a inner function/method of your system, then you add asserts inside Contracts to assert your code contains no bugs. If your f is a function/method that's on an "interface" border, so it's used by other users, then you may want to use enforce instead.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list