break with short circuit

Hello, I was writing a while loop, and inside the loop I alter the variable that's being used to check if the loop should continue. Then there's an expensive calculation, which I can optionally skip once at the end of the loop to save performance, using if/else to check if the loop can end, and breaking if it doesn't need to run anymore. However, I wanted to turn that if/else into a short circuit operation, and discovered that apparently you can't break out of a loop with a short circuit; it has to be using if/else. After researching, apparently this applies to ternary operators as well. I propose that we allow the break function to be used in more cases like this. Thank you!

Example code of the proposed syntax:

while (remaining > half) {
        remaining -= 2 
        (remaining <= half) && break //for optimization, skip loop before calculation
        /*
        -very expensive calculation-
       */
}

How it needs to be done currently:

while (remaining > half) {
       remaining -= 2 
       if (remaining <= half) //for optimization, skip loop before calculation
       {
       break
       } else {
        /*
        -very expensive calculation-
       */
      }
}

&& is a value selection operator, and an if/else is the proper way to do it.

break is a statement, and making it into an expression would greatly complicate the parsing of the language, only so you can abuse value selection operators for flow control :-) i don't think it's worth the complexity.

1 Like

But, there is plans on allowing you to use break in an expression position, thanks to the do expressions proposal. It would look like this:

condition && do { break }

However, like @ljharb said, if is the correct tool for this specific job, there's no real advantage to using && except to save a couple of characters and obfuscate your code a bit (and you won't even save those characters if you use the do-expression proposal).

while (remaining > half) {
       remaining -= 2 
       if (remaining <= half)  break
        // very expensive calculation
}

How is your proposed solution any concise than this;
As far as optimisation goes, I believe the compiler is clever enough make it efficient.

1 Like

A line starting with if is much more readable than a && hidden somewhere in the line. Write better and more maintainable code, do not (attempt to) abuse short-circuiting operators for control flow.
Using

if (remaining <= half) break;

is just as short as the proposed

(remaining <= half) && break;