You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中label标签与goto用法报错:声明无存储类或类型说明符

问题原因
  • 核心错误1:C++语法规定标签只能定义在函数内部的代码块中,你将START:定义在全局作用域(所有函数之外),编译器会将其识别为未声明类型的变量/函数,因此抛出无存储类或类型说明符的错误,和返回值为void的函数无关。
  • 核心错误2:goto不支持跨函数跳转,即使你把标签放到全局,也无法从convertInputToPlanetType函数内跳转到函数外的标签。
  • 隐藏问题:你的代码缺少程序入口main函数,无法正常运行。
修复方案

建议抛弃goto写法,改用循环实现输入校验逻辑,这也是C++更推荐的写法,代码可读性和可维护性更高,修复后完整代码如下:

#include <iostream>
#include <string>
using namespace std;

double weight;
string planet;
double newWeight;

void getUserInput() {
    cout << "Enter your weight and a planet: ";
    cin >> weight >> planet;
}

bool convertInputToPlanetType() {
    if (planet == "Mercury") {
        newWeight = weight * 0.4155;
    }
    else if (planet == "Venus") {
        newWeight = weight * 0.8975;
    }
    else if (planet == "Earth") {
        newWeight = weight;
    }
    else if (planet == "Moon") {
        newWeight = weight * 0.166;
    }
    else if (planet == "Mars") {
        newWeight = weight * 0.3507;
    }
    else if (planet == "Jupiter") {
        newWeight = weight * 2.5374;
    }
    else if (planet == "Saturn") {
        newWeight = weight * 1.0677;
    }
    else if (planet == "Uranus") {
        newWeight = weight * 0.8947;
    }
    else if (planet == "Neptune") {
        newWeight = weight * 1.1794;
    }
    else if (planet == "Pluto") {
        newWeight = weight * 0.0899;
    }
    else {
        cout << "Error: Please enter a valid planet name, starting with a capital letter (ie. 'Earth')" << endl;
        return false;
    }
    return true;
}
void outputWeight() {
    cout << "On " << planet << " you would weigh " << newWeight << " pounds!" << endl;
}

int main() {
    // 循环校验输入,直到输入合法为止
    while (true) {
        getUserInput();
        if (convertInputToPlanetType()) {
            break;
        }
    }
    outputWeight();
    return 0;
}

如果非要用goto实现需求,需要把所有相关逻辑放到同一个函数内部,标签也定义在该函数内,不过非常不推荐这种写法,会导致代码流程混乱。

内容的提问来源于stack exchange,提问作者Sid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:45:01