0

I was implementing linked list in c. For it i created a generation() function for making linked list when i call it inside main() the while loop don't work but when i put the generate code block in main it works fine.

#include<stdio.h>
#include<stdlib.h>
void generation(void);
void first(void);
void end(void);
void middle(void);
int n=0;
struct node{
    int data;
    struct node *next;
};
struct node *head,*newnode,*temp,*prevnode;

void main(){
    generation();
    first();
    end();
    middle();
}
void generation(void){
    head=0;
    int choice;
    while(choice){
        newnode=(struct node*)malloc(sizeof(struct node));
        printf("Enter data\n");
        scanf("%d",&newnode->data);
        newnode->next=0;
        if(head==0)head=temp=newnode;
        else{
            temp->next=newnode;
            temp=newnode;
        }
        printf("Enter for going further(0,1)\n");
        scanf("%d",&choice);
        n++;
    }
        temp=head;
        printf("Your data is:\n");
        while(temp!=0){
         printf("Values are %d\n",temp->data);
         temp=temp->next;
         }


}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115

1 Answers1

2

Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically

You're not initializing the choice variable before the loop, thus you don't know what value it contains

More details here What happens to a declared, uninitialized variable in C? Does it have a value?

Bilaboz
  • 71
  • 3