www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - good example of assert as expression ?

reply user1234 <user1234 12.de> writes:
Following a [previous 
thread](https://forum.dlang.org/thread/loojkahtbzigawrscmsr forum.dlang.org),
can you give me good example where the assert expression is useful ?

So far I only see the case where it is used as AndAnd RHS.

```d
void main()
{
     auto lhs()
     {
         extern(C) int rnd;
         return (rnd % 1) + 1;
     }

     lhs() && assert(0);
}
```

I remember an old NG topic where someone asked if D supports the 
"assert idiom".

So seriously assert as an expression just works in this context ?
I mean don't you think it's an obscure feature that could be 
removed ?
Feb 03
next sibling parent reply "Richard (Rikki) Andrew Cattermole" <richard cattermole.co.nz> writes:
On 04/02/2026 8:58 AM, user1234 wrote:
 Following a [previous thread](https://forum.dlang.org/thread/ 
 loojkahtbzigawrscmsr forum.dlang.org), can you give me good example 
 where the assert expression is useful ?
 
 So far I only see the case where it is used as AndAnd RHS.
 
 ```d
 void main()
 {
      auto lhs()
      {
          extern(C) int rnd;
          return (rnd % 1) + 1;
      }
 
      lhs() && assert(0);
 }
 ```
 
 I remember an old NG topic where someone asked if D supports the "assert 
 idiom".
 
 So seriously assert as an expression just works in this context ?
 I mean don't you think it's an obscure feature that could be removed ?
&& isn't useful here, its || I.e. we use it in the form of ``ptr || assert(0)`` for the null check (not exact but close enough).
Feb 03
parent reply user1234 <user1234 12.de> writes:
On Tuesday, 3 February 2026 at 20:01:47 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
 On 04/02/2026 8:58 AM, user1234 wrote:
 [...]
&& isn't useful here, its || I.e. we use it in the form of ``ptr || assert(0)`` for the null check (not exact but close enough).
Ah yes, OrOr. Shame on me.
Feb 03
parent user1234 <user1234 12.de> writes:
On Tuesday, 3 February 2026 at 20:03:31 UTC, user1234 wrote:
 On Tuesday, 3 February 2026 at 20:01:47 UTC, Richard (Rikki) 
 Andrew Cattermole wrote:
 On 04/02/2026 8:58 AM, user1234 wrote:
 [...]
&& isn't useful here, its || I.e. we use it in the form of ``ptr || assert(0)`` for the null check (not exact but close enough).
Ah yes, OrOr. Shame on me.
Initial question still stands however.
Feb 03
prev sibling parent Timon Gehr <timon.gehr gmx.ch> writes:
On 2/3/26 20:58, user1234 wrote:
 Following a [previous thread](https://forum.dlang.org/thread/ 
 loojkahtbzigawrscmsr forum.dlang.org), can you give me good example 
 where the assert expression is useful ?
auto x = c0 ? e0 : c1 ? e1 : c2 ? e2 : assert(0);
 I mean don't you think it's an obscure feature that could be removed ? 
Every feature can be removed. Should it be removed? No.
Feb 04