为什么我会得到“标签只能是语句的一部分,而声明不是语句的一部分".如果我有一个在标签后初始化的变量? [英] Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

查看:228
本文介绍了为什么我会得到“标签只能是语句的一部分,而声明不是语句的一部分".如果我有一个在标签后初始化的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简化代码:

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup:
    char *str = "World\n";
    printf("%s\n", str);
}

我得到一个错误,因为在标签后声明了一个新变量.如果我将内容(主要是初始化)放在标签后的{}块中,则编译成功.

I get an error because a new variable is declared after the label. If I put the content (mainly initialization) after the label in a {} block, compilation succeeds.

我想我理解在发生切换的情况下发生阻塞的原因,但是为什么在标签的情况下也应适用?

I think I understand the reason for the block in case of a switch, but why should it be applicable in case of a label ?

此错误来自gcc编译器

This error is from a gcc compiler

推荐答案

语言标准根本不允许这样做.标签只能跟在语句之后,声明不算作C语言中的语句.解决此问题的最简单方法是在标签后插入一个空语句,这使您不必像以往那样跟踪范围在一个块内.

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
{
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);
}

这篇关于为什么我会得到“标签只能是语句的一部分,而声明不是语句的一部分".如果我有一个在标签后初始化的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆