假设这些代码编译成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 之间的变量,请不要初始化它们(并且仍然违反某些原则).
我最大的问题如上所述,无法跳转到fin标签(第27行错误),错误:从此处(第12和14行错误)和交叉初始化错误(第20行错误),请帮忙!
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Please comply. y/n: ";
std::string answer;
std::cin >> answer;
if (answer == "y"){std::cout << "You were spared." << std::endl; goto fin;}
if (answer == "Miche"){std::cout << "The killers understood that you understood the prophecy, so they took you to their master" << std::endl; goto secret;}
if (answer == "n"){std::cout << "You were brutally killed." << std::endl; goto fin;}
else {std::cout << "You randomly babled " << answer << …Run Code Online (Sandbox Code Playgroud)