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

你。 提交于 2019-12-20 07:55:54

问题


I got a piece of code such that:

int check(int d, char arr[9][9], int rep_arr[45][3]) {

    int p = findProb(d, arr, rep_arr, 0) ;

    if (isIdeal(d, arr) == 1) {

            print_array(d,arr) ;

            return 1 ;

    }

    else if(isIdeal(d,arr) == 0 && p == 0){

            printf("Fail\n") ;

            return 0 ;

    }

    else if (isIdeal(d, arr) == 0 && p != 0) {

            #do something recursively..
    }

where isIdeal(d, arr) can only be equal to 0 or 1 and p can be equal to 0 or another integer . However, the compiler gives me the error that given in the title.

Later I added return 0 at the end of that piece of code.

Now it works but didn't work in a functional manner because what the function returns is really important.

Another crucial thing is that when I add an else block to avoid failures indicated at another topic on that site see more at link, it never entered that else block.However it always return 0 whether I add an else block or not, by which way all the possibilities end up with a return line. How ?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/36757415/warning-control-reaches-end-of-non-void-function-wreturn-type

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