Breaking out of a loop from within a function called in that loop

后端 未结 14 988
盖世英雄少女心
盖世英雄少女心 2020-12-30 20:31

I\'m currently trying to figure out a way to break out of a for loop from within a function called in that loop. I\'m aware of the possibility to just have the

14条回答
  •  一向
    一向 (楼主)
    2020-12-30 20:41

    (Note: the question has been edited since I originally wrote this)

    Because of the way C is compiled it must know where to break to when the function is called. Since you can call it from anywhere, or even somewhere a break makes no sense, you cannot have a break; statement in your function and have it work like this.

    Other answers have suggested terrible solutions such as setting a global variable, using a #define or longjumping(!) out of the function. These are extremely poor solutions. Instead, you should use the solution you wrongly dismiss in your opening paragraph and return a value from your function that indicates the state that you want to trigger a break in this case and do something like this:

    #include 
    
    bool checkAndDisplay(int n)
    {
        printf("%d\n", n);
        return (n == 14);
    }
    
    int main(void) {
        for (int i = 0; i <= 100; i++) {
            if (checkAndDisplay(i))
                break;
        }
        return 0;
    }
    

    Trying to find obscure ways to achieve things like this instead of using the correct way to achieve the same end result is a surefire way to generate dire quality code that is a nightmare to maintain and debug.

    You mention, hidden in a comment, that you must use a void return, this is not a problem, just pass the break parameter in as a pointer:

    #include 
    
    void checkAndDisplay(int n, bool* wantBreak)
    {
        printf("%d\n", n);
        if (n == 14)
            wantBreak = true;
    }
    
    int main(void) {
        bool wantBreak = false;
        for (int i = 0; i <= 100; i++) {
            checkAndDisplay(i, &wantBreak);
            if (wantBreak)
                break;
        }
        return 0;
    }
    

    Since your parameters are fixed type I suggest you use a cast to pass in the pointer to one of the parameters, e.g. foo(a, b, (long)&out);

提交回复
热议问题