简体   繁体   English

如何修复“错误:控制到达非空函数结束”?

[英]How to fix "error: control reaches end of non-void function"?

int climbStairs(int n ){

    if(n==1){
        return 1;
    }
    if (n>=2){
         return (2+ climbStairs(n-2)+ climbStairs(n-1));
    }
}

在此处输入图片说明

How do I fix the compiler error?如何修复编译器错误?

Your compiler is not as clever as you.你的编译器没有你那么聪明。 You may well know that the function is never called with n less than 1, but the compiler doesn't.您可能很清楚,函数永远不会在n小于 1 时被调用,但编译器不会。 Personally I think it's called with n as 0 for typical inputs.我个人认为对于典型的输入,它被称为n0

Therefore it thinks that program control can reach the function closing brace } without an explicit return, which formally is undefined behaviour if you make use of the function return value which, to repeat, I think you do.因此,它认为程序控制可以在没有显式返回的情况下到达函数右大括号} ,如果您使用函数返回值,那么在形式上是未定义的行为,重复一遍,我认为您这样做了。

You have this warning the compiler issues to you elevated to an error, so compilation halts.您收到此警告,编译器向您发出的警告提升为错误,因此编译停止。

Some fixes:一些修复:

  1. Block the recursion with the stronger if (n <= 1){ .用更强的if (n <= 1){阻止递归。

  2. Run-time assert before the closing brace } using assert(false) or similar.使用assert(false)或类似方法在右大括号}之前运行时断言。

  3. Switch off the elevation of that warning to an error, but do deal with the warning nonetheless.关闭将该警告提升为错误,但仍要处理该警告。


Some advice from @JonathanLeffler来自@JonathanLeffler 的一些建议

Don't switch off -Werror — it is too valuable.不要关闭 -Werror - 它太有价值了。 Deal with the warning.处理警告。 assert(n >= 0);断言(n >= 0); at the top;在顶部; if (n <= 1) { return 1;如果 (n <= 1) { 返回 1; } as well.以及。 Assertions fire in debug builds;断言在调试版本中触发; erroneous parameter value handled reasonably safely and sanely even if assertions are not enabled.即使没有启用断言,错误的参数值也可以合理安全和理智地处理。

And in addition to other answers here is another good trick.除了这里的其他答案之外,还有一个很好的技巧。

If you are absolutely certain that you know more than the compiler, and there's nothing to return, then put an abort();如果你绝对确定你知道的比编译器多,而且没有什么可返回的,那么放一个abort(); as the last line of your function.作为函数的最后一行。 The compiler is smart enough to know that abort() will never return because it causes a program crash.编译器足够聪明,知道abort()永远不会返回,因为它会导致程序崩溃。 That will silence the warning.这将使警告静音。

Note that the program crash is a good thing.请注意,程序崩溃是一件好事。 Because as in this case, when the "impossible thing" does indeed happen, you get the crash and it will pop open in your debugger if you are using one.因为在这种情况下,当“不可能的事情”确实发生时,您会崩溃,并且如果您正在使用调试器,它将在您的调试器中弹出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM