简体   繁体   English

递归函数抛出非空函数警告结束

[英]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.我确保这个函数总是返回一些东西(所有指针都用 nullptr 初始化),但我不希望这个警告不断弹出。 If I add a return nullptr at the end of the function, then it just crashes.如果我在函数的末尾添加一个 return nullptr,那么它就会崩溃。 Is there any way around this?有没有办法解决?

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.在这种情况下,当您递归调用 replaceValue 时,您将丢弃该调用的返回值,然后从函数底部掉出而不返回任何内容。

You probably want to use return replaceValue instead.您可能想改用return replaceValue

Although it's a very old question still I will answer it .虽然这是一个非常古老的问题,但我仍然会回答它

It is like not providing a default case to a switch statement.这就像没有为switch语句提供默认情况。 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.如果您不想这样做,您可以随时使用不返回任何内容的void函数。

You should consider adding a return statement like this so that after the recursive call a value is returned.您应该考虑添加这样的 return 语句,以便在递归调用之后返回一个值。

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.但是如果你确定你的函数处理了所有的极端情况并且控件永远不会达到默认值,那么你可以像这样在最后添加return x The return x here is just to suppress the error message and nothing else in your case.:这里的return x只是为了抑制错误消息,在你的情况下没有别的。:

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

        return x;               // Default value

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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