user8633400
user8633400

Reputation:

Control reaches end of non void function (c++) using while loop

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

Upvotes: 0

Views: 431

Answers (2)

Bathsheba
Bathsheba

Reputation: 234865

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?

Upvotes: 2

Slava
Slava

Reputation: 44268

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

Upvotes: 6

Related Questions