Home > OS >  Why do I get an unused variable error for one variable but not the other even though in principle th
Why do I get an unused variable error for one variable but not the other even though in principle th

Time:12-11

I'm trying to build a linked list and for some reason I get an unused variable error when I create a newNode. What puzzles me is that when I create the head I don't get such an error. Can somebody explain what I'm doing wrong here.

And another thing, for some reason after the first iteration of the loop, it starts to print Input: twice.

int main()
{
    char input[1];
    struct node *head = NULL;
    struct node *newNode = NULL;

    do {
        printf("\nInput: ");
        scanf(" %c", input);

        if(strcmp(input, "=") != 0) {
            if(head == NULL) {
                
                //no error
                head = addLast(head, inputToNode(input));
            }
            else {
                //error
                newNode = addLast(head, inputToNode(input));
            }
        }

    } while(strcmp(input, "=") != 0);

    return 0;
}

The error I get is "error: variable 'newNode' set but not used [-Werror=unused-but-set-variable]"

CodePudding user response:

You are just assigning some data to NewNode, can you see somewhere in your code where NewNode is used ? I don't.

You should always work on the same variable, either head or NewNode. For example, if your head == NULL your code behaves well, perfect. Now, if head already exists, you just want to append your new node to head:

head = addLast(head, inputToNode(input))

If you do:

NewNode = addLast(head, inputToNode(input))

NewNode will always be of length 2, because you will never modify head, which will always only contains the first input, and NewNode will contain as second element the inputToNode(input)

CodePudding user response:

... when I create the head I don't get such an error.

head is potentially read after the assignment read (if(head == NULL)) where as newNode is read after it is assigned.

  • Related