0

I've already researched this but I still don't understand clearly the issue. So, I have this code:

int is_negative(int a)
{
    if(a < 0)
    return a;
    else while (a>=0)
    {
        cout << "Insert a negative value, please: ";
        cin >> a;
        if(a < 0)
            return a;
    }
 }

This function is called in the main function because I want the user to enter a negative number, and to store the value only if it's negative. If it's not, I want it to loop until a negative one is entered.

Why am I getting the error :"Control reaches end of non void function [-Wreturn-type]"? Thanks! :)

PS. I have to use simple syntax like a while or a for loop (exercise requires to do so).

1
  • Since your question is "why" and not "what can I do", I'll leave this as a comment, but I think I can help. If you start with while(a >= 0), anything following that block implicitly has a < 0, and if a < 0, the loop is never entered. You can safely return your value as the closing line. If you like recursion, this wouldn't be a bad time for it; instead of looping, you can simply call the same function again: if(a >= 0) { ...; cin >> a; return is_negative(a); } return a; Commented Jun 29, 2018 at 13:28

2 Answers 2

6

Problem is that compiler cannot detect that loop will never let execution flow to reach behind it, it is not that smart. On another side you could just write while( true ) to avoid confusion.

But the best just change your function to:

int is_negative(int a)
{
    while (a>=0)
    {
        cout << "Insert a negative value, please: ";
        cin >> a;
    }
    return a;
 }

It does exactly the same, but simpler, more readable and would not confuse compiler anymore.

Note: you should check if cin closed and act accordingly, or you may enter infinite loop

Sign up to request clarification or add additional context in comments.

1 Comment

What happens if you enter a non-digit string?
2

It's only a warning and although your compiler is doing its best, you have outsmarted it on this particular occasion. Yes, the final brace is never reached.

You have three options:

  1. Accept you're clever and know what you're doing.
  2. Switch off the warning for the duration of the function.
  3. Refactor the code. Some software houses dislike a function with more than one return anyway, for good reason.

I'd plump for 3 if I were you. Note that if a was a double, then the closing brace could be reached if the input value of a was NaN!

The science of statement reachability is a complex one. For more reading see https://en.wikipedia.org/wiki/Halting_problem

I also can't resist plugging one of my answers here: Does this function have explicit return values on all control paths?

1 Comment

Thanks for the explanation! (The first option made me laugh lol) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.