Variable declaration after goto Label

前端 未结 7 2240
我在风中等你
我在风中等你 2020-12-04 15:20

Today I found one interesting thing. I didn\'t know that one can\'t declare a variable after a goto label.

Compiling the following code

#include <         


        
相关标签:
7条回答
  • 2020-12-04 15:34

    If you know why you can't create variables inside case statement of switch, basically its the same reason why you cant do this too. As a fix, you can try this,

    #include <stdio.h>
    int main() {
        int x = 5;
        goto JUMP;
        printf("x is : %d\n",x);
    JUMP:
        {                                              //Note this
           int a = 0;  // <=== no more error..
           printf("%d",a);
        }                                             //Note this
    }
    
    0 讨论(0)
  • 2020-12-04 15:36
    #include <stdio.h>
    int main() {
        int x = 5;
        goto JUMP;
        printf("x is : %d\n",x);
    JUMP:
        printf("Do anything after label but dont declare 
        anything. even empty statement will also work 
        because label can only be part of a statement");
        int a = 0;  
        printf("%d",a);
    }
    
    0 讨论(0)
  • 2020-12-04 15:40

    My gcc version (4.4) is giving this compile error:

    t.c:7: error: a label can only be part of a statement and a declaration is not a statement
    

    . This error-message says it all.

    0 讨论(0)
  • 2020-12-04 15:40

    Well, first you should be consistent. It's either LABEL or label. Second, label is a part of the statement and the declaration doesn't answer the description enough.

    You can replace LABEL: with label: ; and then it is likelier to compile.

    EDIT: Now that you edited your code all over, it should be JUMP: replaced with JUMP: ; ;-)

    0 讨论(0)
  • 2020-12-04 15:42

    The syntax simply doesn't allow it. §6.8.1 Labeled Statements:

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

    Note that there is no clause that allows for a "labeled declaration". It's just not part of the language.

    You can trivially work around this, of course, with an empty statement.

    JUMP:;
    int a = 0;
    
    0 讨论(0)
  • 2020-12-04 15:48

    You want a semi-colon after the label like this:

     #include <stdio.h>
     int main() {
         int x = 5;
         goto JUMP;
         printf("x is : %d\n",x);
     JUMP: ;     /// semicolon for empty statement
         int a = 0; 
         printf("%d",a);
     }    
    

    Then your code compiles correctly for the C99 standard, with gcc -Wall -std=c99 -c krishna.c (I'm using GCC 4.6 on Debian/Sid/AMD64).

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