What does “control reaches end of non-void functio

2019-01-06 19:10发布

I've been getting strange compiler errors on this binary search algorithm. I get a warning that control reaches end of non-void function. What does this mean?

int binary(int val, int sorted[], int low, int high) {
    int mid = (low+high)/2;

    if(high < low)
        return -1;

    if(val < sorted[mid])
        return binary(val, sorted, low, mid-1);

    else if(val > sorted[mid])
        return binary(val, sorted, mid+1, high);

    else if(val == sorted[mid])
        return mid;
}

5条回答
虎瘦雄心在
2楼-- · 2019-01-06 19:28

The compiler cannot tell from that code if the function will ever reach the end and still return something. To make that clear, replace the last else if(...) with just else.

查看更多
小情绪 Triste *
3楼-- · 2019-01-06 19:31

Always build with at least minimal optimization. With -O0, all analysis that the compiler could use to determine that execution cannot reach the end of the function has been disabled. This is why you're seeing the warning. The only time you should ever use -O0 is for step-by-line debugging, which is usually not a good debugging approach anyway, but it's what most people who got started with MSVC learned on...

查看更多
太酷不给撩
4楼-- · 2019-01-06 19:42

I had the same problem. My code below didn't work, but when I replaced the last "if" with "else", it works. The error was: may reach end of non-void function.

int shifted(char key_letter)
  {
        if(isupper(key_letter))
        {
            return key_letter - 'A'; 
        }

        if(islower(key_letter)   //<----------- doesn't work, replace with else

        {                                            


            return key_letter - 'a'; 
        }

  }
查看更多
来,给爷笑一个
5楼-- · 2019-01-06 19:47

add to your code:

"#include < stdlib.h>"

return EXIT_SUCCESS;

at the end of main()

查看更多
看我几分像从前
6楼-- · 2019-01-06 19:48

The compiler isn't smart enough to know that <, >, and == are a "complete set". You can let it know that by removing the condition "if(val == sorted[mid])" -- it's redundant. Jut say "else return mid;"

查看更多
登录 后发表回答