user1683333
user1683333

Reputation:

Unused variable in C

I'm currently coding a LinkedList implementation in C. I'm stumbling on the following problem: variable 'currentNode' set but not used.

I don't really understand this. I'm using the currentNode variable!

This is my code:

#include <stdio.h>
#include <stdlib.h>

struct node {
    int val;
    struct node * next;
};

int main()
{
    struct node root;
    root.val = 0;
    root.next = NULL;

    struct node currentNode;
    currentNode = root;

    int i;
    for (i = 0; i < 10; ++i)
    {
        struct node newNode;
        newNode.val = i;
        currentNode.next = &newNode;

        currentNode = newNode;
    }

    return 0;
}

Upvotes: 0

Views: 760

Answers (3)

arbboter
arbboter

Reputation: 360

i found another problem.

#include <stdio.h>
#include <stdlib.h>

struct node {
    int val;
    struct node * next;
};

int main()
{
    struct node root;
    root.val = 0;
    root.next = NULL;

    struct node currentNode;
    currentNode = root;

    // .... 
    int i;
    for (i = 0; i < 10; ++i)
    {
        // newNode is a temporary value, 
        // its life time end before the next cycle 
        // u should new it 
        struct node newNode;
        newNode.val = i;
        currentNode.next = &newNode;

        currentNode = newNode;
    }

    // ...maybe like this 
    int i;
    for (i = 0; i < 10; ++i)
    {
        struct node* pNewNode = (struct node*)malloc(siof(struct node));
        pNewNode->val = i;
        currentNode.next = pNewNode;

        currentNode = *pNewNode;
    }

    // free node
    // ... 

    return 0;
}

Upvotes: 0

merlin2011
merlin2011

Reputation: 75585

First of all, you should probably mention that this warning only happens if you use -Wall or specifically -Wunused-but-set-variable.

Second, gcc's definition of usage is reading from a variable, not assigning to a variable.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477338

You are never reading the currentNode variable. If you removed all lines that mention the variable, your program would be exactly the same.

(This is indeed a useful warning: in your case, which presumably was intended to build up a list of ten elements, it points to a fatal bug in your code which means that the actual code does nothing.)

Upvotes: 5

Related Questions