How to do conditional scope(exit) ?

mzfhhhh mzfhhhh at foxmail.com
Thu Dec 19 01:03:56 UTC 2024


On Wednesday, 18 December 2024 at 22:16:45 UTC, John Dougan wrote:
> As the subject. The obvious way:
> I want the  `scope exit 2` to come after the `F`. Is there a 
> way to tell it that I want to use an enclosing scope or make it 
> ignore the scope on the `if`?
>
> Cheers,
>   -- John

This code can make "scope exit 2" be output at the end.

```d
import core.stdc.stdio;
import std;

enum exitcb = `scope void delegate() exitcb;
scope(exit) if(exitcb) exitcb();`;

int test(int val)
{
     mixin (exitcb);

     writeln("A");
     if (val % 2 == 0)
     {
         writeln("b");
         scope (exit)
            exitcb = { writeln("scope exit ", val); };
         writeln("c");
     }
     writeln("F");
     return 2 * val;
}

void main()
{
     writeln("== start =========================");
     int v1 = test(1);
     writeln("== 2 ==============================");
     int v2 = test(2);
     writeln("== end ===========================");
}
```


More information about the Digitalmars-d-learn mailing list