Search code examples
cstandardsc99goto

Can't have label on mid-stream declaration in C?


So this in C99:

label:
  int ret = function(of, stuff);

gives a compile-time error, whereas this:

label:
  ;
  int ret = function(of, stuff);

works just fine.

Is this a compiler bug? Or is this a bug in the definition of the C standard? Or if this is part of the C99 standard, perhaps someone would rise to the defense of the C standard to claim that this makes perfect sense?


Solution

  • Labels, which are defined in N1256 6.8.1 Labeled statements, can only contain statements.

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

    int ret = function(of, stuff); is an declaration, which is defined in N1256 6.7 Declarations and isn't a statement.

    Statements are defined below in N1256 6.8 Statements and blocks:

     Syntax
    1      statement:
               labeled-statement
               compound-statement
               expression-statement
               selection-statement
               iteration-statement
               jump-statement
    

    compound-statement is so-called blocks, which is 0 or more declarations and statements surrounded by {}.

    expression-statement is zero or one expression defined in N1256 6.5 Expressions, followed by a semicolon like i++;. The expression in the syntax is defined in N1256 6.5.17 Comma operator.

    selection-statement is if and switch statement.

    iteration-statement is while, do-while and for statement.

    jump-statement is goto, continue, break and return statement.

    As you see, declarations are not a statement, so you cannot put labels to declarations.