void Stop() {
break;
}
int main() {
while (true) {
std::cout << "NO!" << '\n';
Stop();
}
std::cout << "YES!";
}
In my project I need to end while using a function, how can I change this uncompilable example?
I have an idea to use throw, but what about other better solutions?
You can't really do this. Using exceptions for managing control flow and business logic is considered to be a bad practice in any programming language. What you can do, you could return a boolean flag for breaking out of the loop, for example, when this condition is too complex to be coded directly in the loop:
bool Stop(int idx) {
return idx > 10;
}
int main() {
int counter = 0;
while (true) {
std::cout << "NO!" << '\n';
const bool is_invalid = Stop(counter);
if (is_invalid) break;
++counter;
}
std::cout << "YES!";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With