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

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

    If you cannot use the break instruction you could define a local variable in your module and add a second run condition to the for loop. For example like the following code:

    #include 
    #include 
    
    static bool continueLoop = true;
    
    void foo (int a)
    {
        bool doBreak = true;
    
        printf("a: %d",a);
    
        if(doBreak == true){
            continueLoop = false;
        }
        else {
            continueLoop = true;
        }
    }
    int main(void) {
        continueLoop = true;   // Has to be true before entering the loop
        for (int i = 0; (i <= 100) && continueLoop; i++)
        {
            foo(i);
        }
        return 0;
    }
    

    Note that in this example this is not exactly a break-instruction, but the forloop will not do another iteration. If you want to do a break you have to insert an if-condition with the variable continueLoop which leads to break:

    int main(void) {
        continueLoop = true;   // Has to be true before entering the loop
        for (int i = 0; i <= 100; i++)
        {
            foo(i);
            if(!continueLoop){
                break;
            }
        }
        return 0;
    }
    

提交回复
热议问题