Reputation: 1089
I'm working on a bool function that returns true if found a number on a linked list and false if not, unfortunately this code generates error
The ERROR:
contains.c:24:1: error: control may reach end of non-void function [-Werror,-Wreturn-type] } ^ 1 error generated.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 10
//make a struct called node
typedef struct nodes{
int n;
struct nodes* next;
}node;
//initiate a pointer to the node type
node* head=NULL;
//search function
bool search(int number){
//traverse the list
for(node* conductor=head;conductor!=NULL;conductor=conductor->next){
if(conductor->n==number){
return true;
exit(0);
}
return false;
}
}
//main function
int main(void){
//make the linked list
for(int i=0;i<SIZE;i++){
node* new=malloc(sizeof(node));
if(new==NULL){
exit(0);
}
//initiate the new node
new->n=i;
new->next=head;
head=new;
}
printf("The linked list is ready\n");
printf("Please enter the number you are looking for:\n");
int number;
scanf("%i",&number);
if(search(number)){
printf("found\n");
}
else{
printf("Sorry, not found in the list. The list only contains:\n");
}
//printing the list components
for(node* conductor=head;conductor!=NULL;conductor=conductor->next){
printf("%i ",conductor->n);
}
printf("\n");
return 0;
}
so, I don't know where is the error?
Upvotes: 1
Views: 439
Reputation: 106012
search
function should be like
bool search(int number){
//traverse the list
for(node* conductor=head;conductor!=NULL;conductor=conductor->next){
if(conductor->n==number){
return true;
}
}
// If not found
return false;
}
Place return false;
statement out of for
loop body. exit(0);
in for
is a statement with no effect and will never execute.
Upvotes: 1
Reputation: 20244
The function search
has a return type bool
. You have to return a bool
. If the condition in the for
loop is false, then nothing will be returned. This is what your compiler is complaining about. You probably wanted return false;
outside the body of the if
.
exit(0)
after return true;
in the function search
will never execute.
Upvotes: 1