控制路径不返回值3

时间:2014-04-12 01:05:49

标签: c++

它给我一个错误,说不是所有的控制路径都返回一个值:请帮忙。

int using_range()
{
    int Num;

    try{
        cout << "Please enter a integer between 1 and 10: ";
        cin >> Num;
        if ((Num > 10) || (Num < 0)){
            throw 77;
        }
        else if ((Num <= 10) || (Num >= 0)){
            cout << Num << " is in range\n";
            return 0;
            system("pause");
        }
    }
    catch (int x){
        cout << "The number cannot be greater than 10, or less than zero. Error " << x << endl;
        system("pause");
        return 0;
    }
}

我不知道该怎么做

2 个答案:

答案 0 :(得分:0)

问题是你有一个if后跟一个else if,但是如果这两个检查都失败了,那么默认情况下没有任何内容可以返回。您的代码应该防止这种情况发生,但编译器不够聪明,不能100%确定您将永远不会失败if两个检查。

try{
    cout << "Please enter a integer between 1 and 10: ";
    cin >> Num;
    if ((Num > 10) || (Num < 0)){
        throw 77;
    }
    else if ((Num <= 10) || (Num >= 0)){
        cout << Num << " is in range\n";
        return 0;
        system("pause");
    }
    // <- if you get here, nothing is going to be returned
 }

另一种方法可能是将您的else if更改为else

答案 1 :(得分:0)

所以,只是一个简单的解释:如果你有一个期望返回值的函数(在你的情况下,int),编译器很高兴程序中的所有路径实际上这样做。在此代码中,可能可能会落后于ifelse if,在这种情况下,它不会执行任何操作。如果你愿意,可以在这里抛出错误。

但我想补充的另一件事是在接收用户输入时添加一些保护。也就是说,确保用户输入了一个数字!

目前,如果用户输入b,则输出为0 is in range

因此,请添加另一项检查以确定:

int using_range()
{
    int Num;

    try{
        cout << "Please enter a integer between 1 and 10: ";
        cin >> Num;

        // this checks if whatever the user input can be parsed as an int.
        if (!cin){
           cout << "please enter a number." << endl;
           return -1;
        }
        else if ((Num > 10) || (Num < 0)){
            throw 77;
        }
        else if ((Num <= 10) || (Num >= 0)){
            cout << Num << " is in range\n";
            return 0;
            system("pause"); // also, this will never happen :)
        }
        else{
            // not sure how it could get here, but maybe in weird corner cases?
            return -1;
        }
    }
    catch (int x){
        cout << "The number cannot be greater than 10, or less than zero. Error " << x << endl;
        system("pause");
        return 0;
    }
}