C/C++: goto into the for loop

前端 未结 7 1597
一向
一向 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:17

    Seems perfectly legal.

    From a draft of the C99 standard http://std.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.htm in the section on the goto statement:

    [#3] EXAMPLE 1 It is sometimes convenient to jump  into  the
       middle  of  a  complicated set of statements.  The following
       outline presents one possible approach to a problem based on
       these three assumptions:
    
         1.  The  general initialization code accesses objects only
             visible to the current function.
    
         2.  The  general  initialization  code  is  too  large  to
             warrant duplication.
    
         3.  The  code  to  determine  the next operation is at the
             head of the loop.  (To  allow  it  to  be  reached  by
             continue statements, for example.)
    
               /* ... */
               goto first_time;
               for (;;) {
                       // determine next operation
                       /* ... */
                       if (need to reinitialize) {
                               // reinitialize-only code
                               /* ... */
                       first_time:
                               // general initialization code
                               /* ... */
                               continue;
                       }
                       // handle other operations
                       /* ... */
               }
    

    Next, we look at the for loop statement:

    [#1]  Except for the behavior of a continue statement in the |
       loop body, the statement
    
               for ( clause-1 ; expr-2 ; expr-3 ) statement
    
       and the sequence of statements
    
               {
                       clause-1 ;
                       while ( expr-2 ) {
                               statement
                               expr-3 ;
                       }
               }
    

    Putting the two together with your problem tells you that you are jumping past

    i=0;
    

    into the middle of a while loop. You will execute

    ...process data...
    

    and then

    i++;
    

    before flow of control jumps to the test in the while/for loop

    i

提交回复
热议问题