C/C++: goto into the for loop

前端 未结 7 1615
一向
一向 2021-02-13 21:14

I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this c

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-13 21:19

    If I understand correctly, you're trying to do something on the order of:

    • The first time foo is called, it needs to request some data from somewhere else, so it sets up that request and immediately returns;
    • On each subsequent call to foo, it processes the data from the previous request and sets up a new request;
    • This continues until foo has processed all the data.

    I don't understand why you need the for loop at all in this case; you're only iterating through the loop once per call (if I understand the use case here). Unless i has been declared static, you lose its value each time through.

    Why not define a type to maintain all the state (such as the current value of i) between function calls, and then define an interface around it to set/query whatever parameters you need:

    typedef ... FooState;
    
    void foo(FooState *state, ...)
    {
      if (FirstCall(state))
      {
        SetRequest(state, 1);
      }
      else if (!Done(state))
      {
        // process data;
        SetRequest(state, GetRequest(state) + 1);
      }
    }
    

提交回复
热议问题