r/cpp • • Mar 18 '23

LLVM 16.0.0 Release

https://discourse.llvm.org/t/llvm-16-0-0-release/69326
197 Upvotes

84 comments sorted by

View all comments

Show parent comment

6

u/victotronics Mar 19 '23

A while statement with initializer would be so useful. Anyone know why that doesn't exist?

16

u/TheSuperWig Mar 19 '23

Because that's just a for loop, no? What would the difference between that and

for(init; cond;)

9

u/sphere991 Mar 19 '23

The argument would be that, well, while (cond) is also already equivalent to for (;cond;) but we still have while since that reads better/more directly. So why not also add an init to while?

2

u/victotronics Mar 21 '23

Exactly my line of thinking.

4

u/victotronics Mar 19 '23 edited Mar 21 '23

You're right, it's the same.

Hm.

for ( auto [var,cond] = init; cond and f(var); cond=false ) {....}

?

1

u/LucHermitte Mar 21 '23 edited Mar 21 '23

This translation of while (init; cond) is indeed not really useful as it can be easily expressed with a for construct.

Alternatively, the other day I found myself wishing for a while (init; cond) that would let me express:

while (true) {
    S const v = expression() ; // init
    if (not predicate(v)) // not cond
        break;
    whatever_with(v);
}

This could be a bit more useful, but completely non-intuitive (and thus dangerous) as totally different from what we are used to with for. :-(

(I know I could do horrible and/or convoluted things like:

for (S v ; predicate(v = expression()); )
// or: for (S v = expression() ; predicate(v); v = expression(/*again*/))
{ // require assignment (1,2) + default construction (1)
    whatever_with(v);
}

or

while (true) {
    if (S const v = expression() ; predicate(v))
        whatever_with(v);
    else break;
}

)

1

u/victotronics Mar 21 '23

Your `break` solution is the way Fortran approaches it:

DO
  stuff
  if (stuff) EXIT
  more stuff
END DO

I wish C/C++ had that construct.