функция поиска в связанном списке в C

Я работаю над функцией bool, которая возвращает true, если найдено число в связанном списке, и false, если нет, к сожалению, этот код генерирует ошибку

ОШИБКА:

contains.c:24:1: error: элемент управления может достичь конца непустой функции [-Werror,-Wreturn-type] } ^ 1 сгенерирована ошибка.

Код:

#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;
}

так я и не понял где ошибка?


person Mosaaleb    schedule 09.04.2015    source источник


Ответы (2)


Функция search имеет тип возвращаемого значения bool. Вы должны вернуть bool. Если условие в цикле for ложно, то ничего не будет возвращено. Это то, на что жалуется ваш компилятор. Вероятно, вы хотели return false; снаружи тела if.


Кстати, exit(0) после return true; в функции search никогда не будет выполняться.

person Spikatrix    schedule 09.04.2015
comment
@MuhammadEbeid, вы все равно можете принять ответ, нажав зеленую галочку рядом с ним. Вы можете принять один ответ. Это даст некоторую репутацию как отвечающему, так и спрашивающему. - person Spikatrix; 09.04.2015

search функция должна быть такой

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;
}  

Поместите оператор return false; из тела цикла for. exit(0); в for — это оператор, который не имеет никакого эффекта и никогда не будет выполняться.

person haccks    schedule 09.04.2015