Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

node* search(node* root, int data)
   {

    if(root==NULL||root->data==data)
    {
        if(root->data==data)
            cout<<"Found
";
       
            return root;

    }
      
    if(data<root->data) 
       return search(root->left,data);

    if(data>root->data)
       return search(root->right,data);
   }

above code is for searching a key in a binary search tree, it is giving a warning: control reaches end of non-void function[-Wreturn-type]

how to remove this warning ? Thanks in advance

question from:https://stackoverflow.com/questions/65940698/warning-on-searching-function-of-binary-search-tree

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
322 views
Welcome To Ask or Share your Answers For Others

1 Answer

The return type of your function is node*.

From IBM Knowledge Center:

If control reaches the end of a function and no return is encountered, GCC assumes a return with no return value. However, for this, the function requires a return value. At the end of the function, add a return statement that returns a suitable return value, even if control never reaches there.

You are checking 3 conditions in your function - equal, less than and greater than.

So, compiler is curious that if none of them is satisfied, there is ought to be a return statement at the end of the function because the return type of the function is non void.

Just remove the third if block and directly return search(root->right,data); as follows:

node* search(node* root, int data)
{

    if(root==NULL||root->data==data)
    {
        if(root->data==data)
            cout<<"Found
";
    
        return root;
    }
    
    if(data<root->data) 
        return search(root->left,data);

    return search(root->right,data);
}

This will work because, the third condition is already taken care by the above two conditions, i.e., if something is not equal or less than a value, then that is definitely greater than the value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...