Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end a loop with a function?

Tags:

c++

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?

like image 241
fzyier Avatar asked Jul 21 '26 22:07

fzyier


1 Answers

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!";
}
like image 112
CaptainTrunky Avatar answered Jul 24 '26 12:07

CaptainTrunky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!