0
点赞
收藏
分享

微信扫一扫

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


Aug 28 '13 at 19:17








Renan Gemignani

1,083 10 24



 

Wow, that's bizzare. What's the reason behind that ? –  user1952500  Aug 28 '13 at 19:20

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 –  Keith Thompson  Aug 28 '13 at 19:21

It's not generally possible to give reasons –  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 条评论