C++ Logo

std-proposals

Advanced search

Re: [std-proposals] "once" keyword

From: David Brown <david_at_[hidden]>
Date: Wed, 24 May 2023 15:48:34 +0200
On 24/05/2023 14:57, LUCE Jean-Sébastien via Std-Proposals wrote:
> Hello
>
> It is often useful to support multiple cancel conditions, like 'return'
> in a function, but without having to isolate the code in such a function
> (which is called from a single point).
>
> I'm used to write code like
>
> "
> do {
> if (Failed(Condition0))
> break;
> if (Failed(Condition1))
> break;
> Code_to_execute;
> } while (0);
> "
> or
>
> "
> while (Condition0) {
> if (Failed(Condition1))
> break;
> Code_to_execute;
> break;
> };
> "
>
> the example above looks trivial and could be replaced by
> if (Succeeded(Condition0) && Succeeded(Condition1)) {
> Code_to_execute;
> }
>
> Yet with more complex condition codes, writing conditions per line is
> way more readable.
>
> The syntaxe is still "hacked" someway, since "continue" could be used
> wrongly, or final "break" may be forgotten.
>
> I would like "once" behave like do { } while(0);, where only "break"
> (and not "continue") would have a meaning.
>
> for example above could be converted as
> "
> once {
> if (Failed(Condition0))
> break;
> if (Failed(Condition1))
> break;
> Code_to_execute;
> }
> "
>
> "
> once (Condition0) {
> if (Failed(Condition1))
> break;
> Code_to_execute;
> }
> "
>
> "once" could be followed or not by a first condition.
>
> Thanks
>

I think the name "once" is a very bad choice here. I'd expect something
inside a "once" block to be executed only once in the program - it would
be a good keyword for a convenient way to make a single static object of
a one-use class as a way to get code executed in a thread-safe manner
once in the program lifetime.

I think a better idea here would be to propose allowing "break" inside
an "if" statement. That would be simpler, clearer, and have more
potential applications - instead of your "once" you'd write "if (true)",
and instead of "once (condition)" you'd write "if (condition)".

Received on 2023-05-24 13:48:43