转到标签之后变量声明

转到标签之后变量声明

本文介绍了转到标签之后变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我发现一个有趣的事情。我不知道一个人不能goto语句标签之后声明一个变量。

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

编译如下code

#include <stdio.h>
int main() {
    int x = 5;
    goto JUMP;
    printf("x is : %d\n",x);
JUMP:
    int a = 0;  <=== giving me all sorts of error..
    printf("%d",a);
}

给出了这样的错误。

gives errors like

temp.c: In function ‘main’:
temp.c:7: error: expected expression before ‘int’
temp.c:8: error: ‘a’ undeclared (first use in this function)
temp.c:8: error: (Each undeclared identifier is reported only once
temp.c:8: error: for each function it appears in.)

现在是什么背后的逻辑是什么?我听说的一个人不能开关的case语句中创建的变量。由于跳转goto语句的相同的范围(主要功能的范围,在我的情况)里面,我相信,范围是不是一个问题在这里。不过,为什么我收到此错误?

Now what is the logic behind that? I heard that one cannot create variables inside the case statements of switch. Since JUMP is inside the same scope (the scope of main function, in my case) of the goto statement, I believe that scope is not an issue here. But then, why am I getting this error?

推荐答案

的语法根本不允许这样做。 §6.8.1标签的语句:

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;

这篇关于转到标签之后变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:44