无法跳转到标签“ fin”,错误:从此处开始并越过初始化

Mic*_*son 1 c++

我最大的问题如上所述,无法跳转到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 << ", getting yourself killed."; goto fin;}
  secret:
  std::cout << "In order to fully find out if you are the legendary Miche, they took you to their leader."
  << " The master looked you over, and asked you one final question. The master asks you, fish?" << std::endl;

  std::string fish; fish = "none";
  std::cin >> fish;
  if (fish == "fish."){std::cout << "You were put in the throne of the king, where you ruled your near killers and their species for eternity."
  << std::endl; goto fin;}
  else {std::cout << "You failed and were immediately killed." << std::endl; goto fin;}
  goto fin;

  fin:

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ker 5

问题本质上是:

int main() {
    if (whatever)
        goto fin;
    std::string fish;
fin:
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果whatever为true,则goto跳过的构造fish。这是不允许的,因为编译器无法生成明智的代码来销毁fish,这取决于是否执行了goto。

解决方案:不要使用goto。

可能性:

int main() {
    if (whatever)
        goto fin;
    {
    std::string fish;
    }
fin:
    return 0;
Run Code Online (Sandbox Code Playgroud)

在这里,fish在块的末尾被销毁,因此goto不会引起问题(除了其固有的非结构化性质)。

更好:

int main() {
    if (!whatever) {
        std::string fish;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)