c - If Statement in linked list not working as expected -
so have if
statement in getnth
function im trying test. when inserted printf
function, made me notice goes through if
statement if condition not met, however, when remove printf
statement program works flawlessly. explanation appreciated.
notice! not code, im trying study linked lists , changing code around trying learn!
the code:
#include <stdio.h> #include <stdlib.h> #include <assert.h> /* link list node */ struct node { int data; struct node* next; }; /* given reference (pointer pointer) head of list , int, push new node on front of list. */ void push(struct node** head_ref, int new_data) { /* allocate node */ struct node* new_node = (struct node*) malloc(sizeof(struct node)); /* put in data */ new_node->data = new_data; /* link old list off new node */ new_node->next = (*head_ref); /* move head point new node */ (*head_ref) = new_node; } /* takes head pointer of linked list , index arguments , return data @ index*/ int getnth(struct node* head, int index) { struct node* current = head; int count = 0; /* index of node we're looking @ */ int a; while (current != null) { if (count == index) return(current->data); = current->data; printf("\n testing if in linked list, should bring same desired value 4 %d \n ",a); count++; current = current->next; } /* if line, caller asking non-existent element assert fail */ assert(0); } /* drier program test above function*/ int main() { /* start empty list */ struct node* head = null; /* use push() construct below list 1->12->1->4->1 */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); if (head != null) { } /* check count function */ printf("element @ index 3 %d", getnth(head, 3)); getchar(); }
missing braces.
that's why defender of "always add braces".
edit "solution".
the current code is:
while (current != null) { if (count == index) return(current->data); = current->data; printf("\n testing if in linked list, should bring same desired value 4 %d \n ",a); count++; current = current->next; }
without braces, if statement applies next instruction, return(current->data);
if want include multiple instructions if block, must create block, braces.
if (count == index) { return(current->data); = current->data; printf("\n testing if in linked list, should bring same desired value 4 %d \n ",a); }
however, begin return instruction following 2 lines never executed.
reorder instructions print before return.
if (count == index) { = current->data; printf("\n testing if in linked list, should bring same desired value 4 %d \n ",a); return(current->data); }
Comments
Post a Comment