假设这些代码编译成g++:
#include <stdlib.h>
int main() {
int a =0;
goto exit;
int *b = NULL;
exit:
return 0;
}
Run Code Online (Sandbox Code Playgroud)
g++ 会抛出错误:
goto_test.c:10:1: error: jump to label ‘exit’ [-fpermissive]
goto_test.c:6:10: error: from here [-fpermissive]
goto_test.c:8:10: error: crosses initialization of ‘int* b’
Run Code Online (Sandbox Code Playgroud)
似乎goto无法跨越指针定义,但gcc编译好,没有任何抱怨.
修复错误之后,我们必须在任何goto语句之前声明所有指针,也就是说你必须声明这些指针,即使你现在不需要它们(并且违反了一些原则).
什么原因设计考虑g++禁止有用的尾部goto声明?
更新:
goto可以交叉变量(任何类型的变量,不限于指针)声明,但除了那些获得初始化值.如果我们删除NULL上面的任务,g++请立即保持沉默.因此,如果要声明goto-cross-area 之间的变量,请不要初始化它们(并且仍然违反某些原则).