Miss J. Miss J. - 1 month ago 5
C Question

why do I see a compile time error for the below?

I'm trying to do a simple program, adding a node to the end of the link list:

/*Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list

Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/

Node* Insert(Node *head,int data)
{

if(head){
Node *curr_node=head;

while(curr_node->next)
curr_node=curr_node->next;
}

Node *new_node=(Node *)calloc(1,sizeof(Node));
new_node->data=data;
new_node->next=NULL;

if(head)
curr_node->next=new_node;
else
head=new_node;

return head;
}

/* the main function calls it*/


when I compile, I see the following error:

In function ‘Node* Insert(Node*, int)’:
solution.cc:59:13: error: ‘curr_node’ was not declared in this scope
curr_node->next=new_node

why does it say curr_node not declared, when it's actually declared right in the beginning. What am I missing here?

Answer

A variable declared in a function definition has a scope which extends only to the innermost {} braces. So your variable curr_node is no longer valid after the first if block.

To fix this, declare your variable outside the if block:

Node* Insert(Node *head,int data)
{
    Node *curr_node = NULL;
    if(head){
        curr_node=head;

        while(curr_node->next)
            curr_node=curr_node->next;
    }
Comments