Assert allowed to have side effects?

Stewart Gordon smjg_1998 at yahoo.com
Sun May 29 05:21:05 PDT 2011


On 29/05/2011 09:44, simendsjo wrote:
> The documentation for assert,
> http://www.digitalmars.com/d/2.0/expression.html#AssertExpression, states that it's an
> error if the assert expression contains side effects, but it doesn't seem the compiler is
> enforcing this.

There are places where the spec fails to make a clear distinction between illegal code and 
incorrect code that the compiler may reject if it's smart enough.

The point of asserts is to check that the code is working correctly.  By the time you come 
to release your software, you know that it's working correctly, and so the compiler 
ignores asserts in release mode.  So the onus is on you to make sure the asserts don't 
have side effects.

> module assert_sideeffect;
> bool b;
> bool f() { b = !b; return b; }
> void main() {
> assert(f()); // oops.. changes b in debug mode
<snip>

It doesn't depend on debug mode.  It depends on release mode.  They're two independent 
compiler switches.

Stewart.


More information about the Digitalmars-d-learn mailing list