warning: control reaches end of non-void function [-Wreturn-type]

怎甘沉沦 提交于 2019-12-02 13:40:06

If you are sure about the possible values, then you can replace your entire function with:

int foo(int case1, int case2) {
    if (case1 == 1) {
        return val;
    }
    return case2 == 0 ? val2 : val3;
}

and silence your warning at the same time.

If you're concerned case1 may possibly be something other than 1 or 0, then just change to:

int foo(int case1, int case2) {
    assert(case1 == 0 || case1 == 1);

    if (case1 == 1) {
        return val;
    }
    return case2 == 0 ? val2 : val3;
}

The compiler does not know what the values of the case1 and case2 arguments will be. Your if conditions don't handle all possible values that those arguments might hold (ignoring that you may only be passing in 1 and 0). Thus the compiler properly warns you that you can get to the end of the function without returning anything.

If you are truly certain that this should never happen, turn this into a runtime error and put an assert at the end of the function (you may still need to return after the assert to silence the warning, I'm not sure).

int foo(case1, case2) {
    // your if conditions here

    assert(0);
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!