首页 > 解决方案 > unexpected not all control paths return a value?

问题描述

I am currently writing a program in C++ and have created a function called parseText. When i run this function i get the warning "Not all control paths return a value" however after looking at this code multiple times i cannot find out why this is happening. Is this an incorrect error or have i missed something.

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
    }
}

标签: c++visual-c++

解决方案


在这个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
}

推荐阅读