C语言 “控制到达非空函数的末端”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6171500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:48:10  来源:igfitidea点击:

What does "control reaches end of non-void function" mean?

cwarningscompiler-warnings

提问by tekknolagi

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?

我在这个二进制搜索算法上遇到了奇怪的编译器错误。我收到一个警告control reaches end of non-void function。这是什么意思?

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

回答by rid

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.

编译器无法从该代码中判断该函数是否会到达末尾并仍然返回某些内容。为了说明这一点,请将最后一个替换为else if(...)just else

回答by Ernest Friedman-Hill

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

编译器是不够聪明到知道<>==是一个“完整的”。您可以通过删除条件“if(val == sorted[mid])”来让它知道——它是多余的。就说“ else return mid;

回答by R.. GitHub STOP HELPING ICE

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 -O0is 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...

始终以最少的优化进行构建。使用-O0,编译器可以用来确定执行无法到达函数末尾的所有分析都已被禁用。这就是您看到警告的原因。您应该使用的唯一时间-O0是逐行调试,无论如何这通常不是一个好的调试方法,但这是大多数开始使用 MSVC 的人在...

回答by Thuy

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.

我有同样的问题。我下面的代码不起作用,但是当我用“else”替换最后一个“if”时,它起作用了。错误是:可能到达非空函数的结尾。

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

  }

回答by Donitsky

add to your code:

添加到您的代码中:

"#include < stdlib.h>"

return EXIT_SUCCESS;

at the end of main()

在......的最后 main()