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

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

    I believe it's related to how a break statement is translated into machine code. The break statement will be translated as a unconditional branch to the label immediately following the loop or switch.

    mov ECX,5
    label1:
      jmp <to next instruction address>  ;break
    loop label1
    <next instruction>
    

    While the call to foo() from inside the loop will result in something like

    mov ECX,5
    label1:
      call <foo address>
    loop label1
    <next instruction>
    

    and at foo address

    call <printf address>
    jmp <to where?> ;break cannot translate to any address.
    
    0 讨论(0)
  • 2020-12-30 21:00

    If you cannot handle return values, can you at least add a Parameter to the function: I can imagine a solution like that:

    void main (void)
    {
      int a = 0;
    
      for (; 1 != a;)
      {
        foo(x, &a);
      } 
    }
    
    void foo( int x, int * a)
    {
      if (succeeded)
      {
        /* set the break condition*/
        *a = 1;
      }
      else
      {
        *a = 0;
      }
    }
    

    It's my first post, so, please forgive me, if my formatting is messed up :)

    0 讨论(0)
提交回复
热议问题