Chinaunix

标题: [c] goto语句的疑惑 [打印本页]

作者: inet_addr    时间: 2012-07-05 16:18
标题: [c] goto语句的疑惑
  1. #include <stdio.h>

  2. int main()
  3. {
  4.   int i;
  5.   for(i = 0; i < 100; i++)
  6.   {
  7.     int k;
  8.     for(k = 0; k < 100; k++)
  9.     {
  10.       if(k%3 == 0)
  11.       {
  12.         goto next_file;
  13.       }
  14.     }
  15. next_file:
  16.   }
  17.   return(0);
  18. }
复制代码
$ cc t.c
t.c: In function 'main':
t.c:16: error: label at end of compound statement

-------------------------

$ g++ t.cpp
t.cpp: In function 'int main()':
t.cpp:22: error: expected primary-expression before '}' token
t.cpp:22: error: expected `;' before '}' token

下面的可以正常运行
  1. #include <stdio.h>

  2. int main()
  3. {
  4.   int i;
  5.   for(i = 0; i < 100; i++)
  6.   {
  7.     int k;
  8.     for(k = 0; k < 100; k++)
  9.     {
  10.       if(k%3 == 0)
  11.       {
  12.         goto next_file;
  13.       }
  14.     }
  15. next_file: ;
  16.   }
  17.   return(0);
  18. }
复制代码
next_file是一个标号, 其后为什么非要一个空语句????

gcc: 4.1.2
OS: centos
作者: MMMIX    时间: 2012-07-05 16:21
inet_addr 发表于 2012-07-05 16:18
next_file是一个标号, 其后为什么非要一个空语句????


C 语法就是这么要求/规定的。
作者: inet_addr    时间: 2012-07-05 16:24
MMMIX 发表于 2012-07-05 16:21
C 语法就是这么要求/规定的。


c标准中有吗, 这里这么多人讨论c标准的, 能不能给个原文.

PM~~~~~~
作者: bruceteen    时间: 2012-07-05 16:28
A label name is the only kind of identifier that has function scope. It can be used (in a
goto statement) anywhere in the function in which it appears, and is declared implicitly
by its syntactic appearance (followed by a : and a statement).
作者: inet_addr    时间: 2012-07-05 16:39
bruceteen 发表于 2012-07-05 16:28
A label name is the only kind of identifier that has function scope. It can be used (in a
got ...


ISO_IEC_9899 6.2.1节, 这是说作用域时顺便提到

cc的提示是label at end of compound statement

"{}"是个复合语句, 复合语句也算语句呀(抠字眼的话)

如果那个空语句应该怎么写这段程序呢?
作者: inet_addr    时间: 2012-07-05 16:53
另外, 经常发现g++有类似" expected primary-expression before '}' token"的提示.
   这个primary-expression是什么意思啊,  难道还有secondary-expression这个说法?
作者: MMMIX    时间: 2012-07-05 20:32
inet_addr 发表于 2012-07-05 16:39
"{}"是个复合语句, 复合语句也算语句呀(抠字眼的话)


複合語句是算語句,可你的 label 也沒在這個複合語句之前呀。
作者: tansijie    时间: 2012-07-05 21:11
标签 lable: 就行了,不需要添加;




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2