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

后端 未结 14 976
盖世英雄少女心
盖世英雄少女心 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:52

    In a case like this consider using a while() loop with several conditional statements chained with && instead of a for loop. Although you can alter the normal control flow using functions like setjmp and longjmp, it's pretty much considered bad practice everywhere. You shouldn't have to search too hard on this site to find out why. ( In short it's because of it's capacity to create convoluted control flow that doesn't lend itself to either debugging or human comprehension )

    Also consider doing something like this:

    int foo (int a) {
        if(a == someCondition) return 0;
        else {
            printf("a: %d", a);
            return 1;
        }
    }
    
    int main(void) {
        for (int i = 0; i <= 100; i++) {
            if(!foo(i)) break;
        }
        return 0;
    }
    

    In this case, the loop depends on a true value being returned from 'foo', which will break the loop if the condition inside 'foo' is not met.

    Edit: I'm not explicitly against the use of goto, setjmp, longjmp etc. But I think in this case there is a much simpler and more concise solution available without resorting to these measures!

提交回复
热议问题