In C why do you need a statement after a goto label?

前端 未结 3 1167

I am writing some C code and in my code I have two nested loops. On a particular condition I want to break out of the inner loop and continue the o

相关标签:
3条回答
  • 2020-12-11 00:16

    You simply need to write:

    label: ;
    

    The semi-colon is an empty statement. You need it because the language is defined like that; you need to go to a statement, even if it is an empty one.

        for (int i = 0; i < N; i++)
        {
            for (int j = 0; i < M; j++)
            {
                ...
                if (some_condition)
                    goto continue_loop1;
                ...
            }
    continue_loop1: ;
        }
    

    You can argue about the indentation on the label.

    0 讨论(0)
  • 2020-12-11 00:18

    The label should point to a statement.

    C mandates this:

    (C99, 6.8.1 Labeled statements p4) " Any statement may be preceded by a prefix that declares an identifier as a label name."

    In your case you can use a null statement:

    void foo(void)
    {
        goto bla;
    
        bla:
        ;
     }
    

    Null statements perform no operation.

    Or you can also use a compound statement (a block) if you have declarations:

    void foo(void)
    {
        goto bla;
    
        bla:
        {
            int x = 42;
            printf("%d\n", x);
        }
     }
    
    0 讨论(0)
  • 2020-12-11 00:32

    In the standard it's explicitly said that labels belong to a statement, therefore a simple semicolon (;) after your label can circumvent the problem you are running in to, since that counts as a statement.

    There is even an example of the use of an "empty"1 statement in 6.8.3/6.

    EXAMPLE 3 A null statement may also be used to carry a label just before the closing } of a compound statement

    while (loop1) {
      /* ... */
    
      while (loop2) {
        /* ... */
    
        if (want_out)
          goto end_loop1;
    
        /* ... */
      }
    
      /* ... */
    
      end_loop1: ;
    }
    

    1 In the standard this is referred to as a null statement.


    6.8.1 Labeled statements

    Syntax
      1 labeled-statement:
          identifier : statement
          case constant-expression : statement
          default : statement
    

    Notice that statement isn't optional in the above quotation.


    • open-std.org: n1124.pdf
    0 讨论(0)
提交回复
热议问题