0
int insert(node* head) {
    if (head == NULL) {
        node* temp = new node;
        if (head == NULL) {
            cout << "Error";
            return 0;
        }
        temp->data = 20;
        temp->next = NULL;
    } else {
        temp->next = insert(temp->next);
    }
    return (temp);
}

I am trying to add node recursively but I got the error temp was not declared. I do not understand why I am getting this error. When I always define temp like this node* temp = new node; but now I got an error.

2
  • It doesn't really make sense for insert to return something. Besides, your return type is int but you're returning a node* in return temp. Just make the return type void. Commented Nov 20, 2014 at 4:07
  • @0x499602D2, std::list's insert returns an iterator to the inserted element. Commented Nov 20, 2014 at 4:14

2 Answers 2

1

Local variables are only visible inside the scope they're declared in, and you're declaring temp inside your first if statement. You need to move the definition outside the if clause:

int insert(node* head)
{
     node* temp=new node; // <- move to here
     if(head==NULL)
     {
          ...
     }
     else
     {
          ...
     }
     return temp;
}
Sign up to request clarification or add additional context in comments.

Comments

0

There seems to be multiple issues with your code:

int insert(node* head) { if (head == NULL) { node* temp = new node; // Newly created node will not be used at all if (head == NULL) { // as head is NULL it will return 0 cout << "Error"; return 0; } temp->data = 20; // Code unreachable temp->next = NULL; } else { temp->next = insert(temp->next); // Here you will again get an error for temp not declared } return (temp); }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.