The problem is that the compiler believes that the collatz()
function can finish processing without hitting a return. While it may logically not be possible, compilers are dumb. They can't analyze code well enough to see that all logical possibilities may be covered. Instead, they verify that all paths through the code will end at a return.
Because your code contains all of the returns in a while loop, the compiler sees that if the while loop doesn't start ( n is <= 0 ), no return statement will be executed, so it yells. In this case, there's nothing preventing entry of a negative number for n in main, so the called function can definitely fail because of a path with no return statement. Even if you did force n to be > 0, the compiler wouldn't be smart enough to recognize it.
The solution? Put a catchall return
statement at the end of the function code so that if the code gets to the end, it will execute. Also, be careful about the return value. For example, if the function is searching for something to be true, the catchall should return the opposite - return false. Returning a number? Find a number to return that should never be returned and use it to indicate an error (or find some other mechanism to generate an error).
As for no return in main(), it's not a problem. The best practice is to always end processing with a return statement, but it isn't necessary in main and won't cause a compile error. You can prove this by writing a small test program. Remember the "Hello World" program?
For more detailed explanations, see the following two posts:
How to solve "control may reach end of non void function" error
How to Fix "control may reach end of non-void function" and "No such file or directory" Errors?
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)