c++ - 不是所有控制路径都返回值吗?

标签 c++ visual-c++

我目前正在用C++编写程序,并创建了一个名为parseText的函数。当我运行此函数时,我得到警告“并非所有控制路径都返回一个值”,但是在多次查看此代码后,我无法找出原因。这是一个不正确的错误还是我错过了什么。

int parseText(std::string line, std::string *posResponses) {
    for (int x = 0; x < line.length(); x++) {
        line.at(x) = toupper(line.at(x));
    }
    if (line == "HELP") {
        runHelp(3);
        return 0;           //returns 0 if user entered invalid response and needs to repeat the code
    }else if (line == "QUIT") {
        return 2;           //returns 2 if user wants to quit 
    }
    if (posResponses->size() == 1 && posResponses[0] == line) {
        return 1;           //returns 1 if there was a valid response               
    }else if (posResponses[0] == "int") {
        int x = posResponses[1].size();
        for (int i = 0; i <= x; i++) {
            if (posResponses[1].at(i) < 48 || posResponses[1].at(i) > 57) {
                return 0;   //returns 0 if user entered invalid response and needs to repeat the code
            }
            return 1;       //returns 1 if there was a valid response
        }
    }
    else{
        int x = posResponses->size();
        for (int i = 0; i <= x; i++) {
            if (posResponses[i] == line) {
                return 1;   //returns 1 if there was a valid response
            }
        }
        return 0;           //returns 0 if user entered invalid response and needs to repeat the code
    }
}

最佳答案

在这个if分支中

} else if (posResponses[0] == "int") {
    int x = posResponses[1].size();
    for (int i = 0; i <= x; i++) {
        if (posResponses[1].at(i) < 48 || posResponses[1].at(i) > 57) {
            return 0;   //returns 0 if user entered invalid response and needs to repeat the code
        }
        return 1;       //returns 1 if there was a valid response
    }
}

如果为x分配了值< 0,则根本不会输入for循环,因此该分支没有return语句。

也许您确定x在运行时不会减,但是编译器必须在编译时确认所有分支。

我不确定您的意图,您可能想要
} else if (posResponses[0] == "int") {
    if (posResponses[1].size() == 0 || posResponses[1].at(0) < 48 || posResponses[1].at(0) > 57) {
        return 0;   //returns 0 if user entered invalid response and needs to repeat the code
    }
    return 1;       //returns 1 if there was a valid response
}

关于c++ - 不是所有控制路径都返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61334761/

相关文章:

c++ - CustomDialogEx 的 shared_ptr 或 unique_ptr

c++ - 为什么基于范围的 for 循环中的结构化绑定(bind)只是拷贝而不是引用?

c++模板类成员struct初始化语法糖

c++ - 删除不能正常工作? (标准命名空间的)

c++ - 内联 asm 到 x64 - 理解

c++ - 设置安全信息 : Undeclared Identifier

c++ - 通过 clang-format 格式化 lambda 背后的逻辑是什么?

c++ - Boost ASIO 连接失败

c++ - CPLEX C++ : How to change parameters during optimization

c++ - Boost.Spirit 重叠 Action /重用终端 token