How to replace/optimize multiple ifs in C?

Asked

Viewed 174 times

0

I’m a beginner in C language, I’m doing an activity that is to register students and averages in a double-chained list, everything is working, however I believe I’m using too many ifs, there is some way to do these conditions without using so many ifs?

A part of the code:

int editar(aluno *alunoPtr){
aluno *tmp;
int edita, aux=0;
tmp=alunoPtr->prox;
if(vazia(alunoPtr)){
    printf("A LISTA ESTA VAZIA!!!\n");
}else{
    printf("Numero de matricula: ");
    scanf("%i", &edita);
    while(tmp){
        if(edita == tmp->matricula){
            printf("\nMedia final: ");
            scanf("%f", &tmp->mediaFinal);
            if(tmp->mediaFinal >= 0 && tmp->mediaFinal <= 10){
                printf("\nMEDIA CADASTRADA COM SUCESSO!\n");
            }else{
                printf("\nMEDIA INVALIDA!\n");
            };
            aux++;
            break;
        };
        tmp=tmp->prox;
    };
    if(aux==0){
        printf("\nNUMERO DE MATRICULA INVALIDO!\n");
    };
};

};

1 answer

0


Using Return to return the aux when editing successfully and -1 when an error occurs it is possible to remove the last if and some elses.

   int editar(aluno *alunoPtr) {
     aluno *tmp;
     int edita, aux = 0;
     tmp = alunoPtr->prox;
     if (vazia(alunoPtr)) {
       printf("A LISTA ESTA VAZIA!!!\n");
       return -1;
     }
     printf("Numero de matricula: ");
     scanf("%i", &edita);
     while (tmp) {
       if (edita == tmp->matricula) {
         printf("\nMedia final: ");
         scanf("%f", &tmp->mediaFinal);
         aux++;
         if (tmp->mediaFinal >= 0 && tmp->mediaFinal <= 10) {
           printf("\nMEDIA CADASTRADA COM SUCESSO!\n");
           return aux;
         } 
         printf("\nMEDIA INVALIDA!\n");
         return -1;
       };
       tmp=tmp->prox;
     };
     printf("\nNUMERO DE MATRICULA INVALIDO!\n");
     return -1;
   };

Browser other questions tagged

You are not signed in. Login or sign up in order to post.