user3444650
user3444650

Reputation: 117

Recursive function throwing end of non-void function warning

    Node * replaceValue(Node * x) const
    { 
        if (x == nullptr)
            return nullptr;
        if (x->left != nullptr)
            replaceValue(x->left);
        else
            return x;
    }

Warning: control reaches end of nonvoid function

Should i just ignore this? I made sure that this function always returns something (all pointers initialized with nullptr), but I don't want this warning to keep popping up. If I add a return nullptr at the end of the function, then it just crashes. Is there any way around this?

Upvotes: 0

Views: 1231

Answers (2)

Partha Prateem Patra
Partha Prateem Patra

Reputation: 181

Although it's a very old question still I will answer it.

It is like not providing a default case to a switch statement. When the control reaches the end of your non-void function it doesn't have anything to return, in case all of your conditions fail. I believe the compiler does this so that you take care of all the corner cases and possibilities for the function. For example, if the user enters a value of a datatype which you haven't used in your function then without throwing an exception a default value can be returned instead.

If you don't want to do this you can always use a void function that doesn't return anything.

You should consider adding a return statement like this so that after the recursive call a value is returned.

if (x->left != nullptr)
     return replaceValue(x->left);

But if you are sure that your function takes care of all the corner cases and the control will never reach the default value then you can add return x at the end just like this. The return x here is just to suppress the error message and nothing else in your case.:

    Node * replaceValue(Node * x) const
    { 
        if (x == nullptr)
            return nullptr;
        if (x->left != nullptr)
            replaceValue(x->left);
        else
            return x;          

        return x;               // Default value

    }

Upvotes: 0

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32717

Never ignore a warning. It's telling you something important.

In this case when you call replaceValue recursively, you're throwing away the return value from that call then falling out the bottom of the function without returning anything.

You probably want to use return replaceValue instead.

Upvotes: 5

Related Questions