简体   繁体   中英

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. Personally I think it's called with n as 0 for typical inputs.

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){ .

  2. Run-time assert before the closing brace } using assert(false) or similar.

  3. Switch off the elevation of that warning to an error, but do deal with the warning nonetheless.


Some advice from @JonathanLeffler

Don't switch off -Werror — it is too valuable. Deal with the warning. assert(n >= 0); at the top; if (n <= 1) { return 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(); 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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