a label can only be part of a statement and a declaration is not a statement

在写代码的时候,变量的声明不应该出现在label之后,比如switch语句中的case结构也可能会遇到类似的问题。

PS:从一个#if…#endif宏块goto到宏块以外,会有一个编译告警。

在case下面定义了变量,并给它赋了初值,当把定义和赋值分开就好了,或者是加上大括号。

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);
}
share improve this answer
 
6 
Wow, that's bizzare. What's the reason behind that ? –  user1952500  Aug 28 '13 at 19:20
15 
Prior to C99, all declarations had to precede all statements within a block, so it wouldn't have made sense to have a label on a declaration. C99 relaxed that restriction, permitting declarations and statement to be mixed within a block, but the syntax of a labeled-statement was not changed. –  Keith Thompson  Aug 28 '13 at 19:21
2 
It's not generally possible to give reasons for this kind of language quirk. The grammar is just the way it is. I can look in the C Rationale document ... not till tomorrow, though ... but I probably won't find anything. –  zwol  Aug 28 '13 at 19:21
 
@Zack: thanks for mentioning the C Rationale document. It looks interesting. However in section 6.8.6.1 (The goto statement) the example he uses in the latter approach as an approved mechanism should have failed! –  user1952500  Aug 28 '13 at 19:33


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值