Command "goto" creating infinite loop in "for" loop

Asked

Viewed 768 times

0

I want to simulate a school database that collects name, math and physics grades and averages both for 5 students (defined in a string of struct).

Any grade above 10 would be allowed, without any lock for it. Students would easily have grades above 10. So I thought I’d make a condition with if-else and used the goto, positioning its return at the beginning of the note request.

See the code below:

#include<stdio.h>
#include<locale.h>

int main(void){

setlocale(LC_ALL,"Portuguese");

struct Aluno{
    char nome[10];
    float notaMath, notaPhysics, media;
};

struct Aluno aluno[5];

int contador;

//Entrada de dados via teclado
for(contador = 0; contador < 5; contador++){
    printf("Nome do aluno %d: ", contador+1);
    scanf("%s",&aluno[contador].nome);

    RETORNO1:
    printf("Nota de matemática: ");
    scanf("%f",&aluno[contador].notaMath);
    if(aluno[contador].notaMath > 10.0){
        printf("Apenas notas até 10.\n");
        goto RETORNO1;
    }
    else{
        goto POINT1;
    }

    POINT1:
    RETORNO2:
    printf("Nota de física: ");
    scanf("%f",&aluno[contador].notaPhysics);
    if(aluno[contador].notaPhysics > 10.0){
        printf("Apenas notas até 10.\n");
        goto RETORNO2;
    }
    else{
        goto POINT2;
    }

    POINT2:
    aluno[contador].media = (aluno[contador].notaMath + aluno[contador].notaPhysics)/2;

    printf("\n");
}

printf("\n\n");

printf("------------Informações dos Alunos------------\n");
for(contador = 0; contador < 5; contador++){
    printf("Nome do aluno %d: %s\n", contador+1, aluno[contador].nome);
    printf("Nota de matemática: %.1f\n", aluno[contador].notaMath);
    printf("Nota de física: %.1f\n", aluno[contador].notaPhysics);
    printf("Média das notas: %.1f\n", aluno[contador].media);
    printf("\n\n");
}
}

In this case, by placing any floating point values greater than 10, it prints "only notes up to 10" and actually returns to the set point, all ok. But if I put some floating point value, like 10.5, it goes into loop infinite.

Without the placement of goto and the POINTs and RETORNOs he simply skips most of the following instructions and goes there forward in the loop for.

Example of execution (data copied from .exe):

"Nome do aluno 1: Jonathan
 Nota de matemática: 10.5
 Nota de física:
 Nome do aluno 2: Nota de matemática:"
  • And why don’t you take that goto? I saw no advantage in him.

  • You should take that There really has no advantage...

  • I can even take it off, no problem. But, I wanted to know a way to limit the user to put notes up to 10, and make him return to the insertion of the same note, if he insists on putting a value greater than 10.

  • As far as I know, C forces me to use Else if I use If. If there is a way to use If alone, like in Java, teach me! haha

  • Yes you can remove the if and it is not necessary to put the non Else friend, because you do not have a counteroffer to condition..

  • @Matheus you’re right. I tested it here and If worked alone. I remember from the beginning when I started with Dev Cpp, that he wouldn’t let If roll without Else. I’m using Codeblocks here and I’ve never tested this. It really was Dev’s trauma and lack of curiosity to test if it would work xD

  • Anyway, the Loop error continues :( Any alternative suggestion to limit the user and make him return to the insertion of the same note?

  • I just posted an answer.. See if you can sort of understand her

  • Careful the way you’re using the goto. It’s not a good practice to use it that way. It gets very confusing for another person to understand doing these crazy jumps from one point of the code to the other as Voce did.

  • Mandatory readings on goto: http://bioinfo.uib.es/~joemiro/Teach/material/escritura/gotoharmfulCol.pdf ; http://web.archive.org/web/20090320002214/http://www.ecn.Purdue.edu/Paramount/papers/rubin87goto.pdf

  • Thanks for the @gfleck touch. I’ve read a little about goto and that it’s not cool to use enough, but I couldn’t think of other alternatives. That’s why I came to you haha

  • 1

    Thanks for the reading suggestions, @Jeffersonquesado. I’ll read it all!

  • A life tip: Never use goto!

Show 8 more comments

2 answers

3

The code had some bugs that I fixed. I improved the style a bit too.

goto is almost never suitable. It can almost always be replaced by a if or a while, what is the case. What you clearly want is a repeat loop until the person type the correct one, so make a loop, it’s much simpler. Only exit it when the entered value is valid.

#include <stdio.h>
#include <locale.h>

int main(void) {
    setlocale(LC_ALL,"Portuguese");
    struct Aluno {
        char nome[10];
        float notaMath, notaPhysics, media;
    } aluno[5];
    for (int contador = 0; contador < 5; contador++) {
        printf("Nome do aluno %d: ", contador + 1);
        scanf("%s", aluno[contador].nome);
        while (1) {
            printf("Nota de matemática: ");
            scanf("%f", &aluno[contador].notaMath);
            if (aluno[contador].notaMath > 10.0) printf("Apenas notas até 10.\n");
            else break;
        }
        while (1) {
            printf("Nota de física: ");
            scanf("%f", &aluno[contador].notaPhysics);
            if (aluno[contador].notaPhysics > 10.0) printf("Apenas notas até 10.\n");
            else break;
        }
        aluno[contador].media = (aluno[contador].notaMath + aluno[contador].notaPhysics) / 2;
        printf("\n");
    }
    printf("\n\n------------Informações dos Alunos------------\n");
    for (int contador = 0; contador < 5; contador++) {
        printf("Nome do aluno %d: %s\n", contador+1, aluno[contador].nome);
        printf("Nota de matemática: %.1f\n", aluno[contador].notaMath);
        printf("Nota de física: %.1f\n", aluno[contador].notaPhysics);
        printf("Média das notas: %.1f\n", aluno[contador].media);
        printf("\n\n");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I left the contador, but I prefer i, I find it very verbose, everyone knows what is the i, I find it even more readable. I would have other tips for writing better code, but it escapes the scope of the question.

  • I know the i too. It was more for the sake of taste, but most of the time I write. I understood well, my friend. I’m testing here! Thank you very much

  • Friend, a question. So far I’ve run into this one a couple of times while(1){ } What does this condition mean? I always build Whiles with variables and all that condition of >, <, == etc. Obg now

  • It is possible to make a while with variable there, but I think it gets a worse code. It is a while infinite, only comes out forcibly, the condition is always true (1).

  • your while super worked! Now, the only problem that’s being caused to me and I still can’t figure out how to solve it is the floating point issue, which causes a crazy infinite loop in the run. If you can, try running the full Code there by adding the piece you suggested and at the time of insertion of one of the notes, put a floating point number, like 10.4 or 11.3. See what happens x_x

  • This is another problem, do it one problem at a time. Demonstrate in new question. I can’t imagine how you can cause a loop infinite because of this. Of course values above 10 do not pass the validation, is what you want.

  • Okay, thanks for the tips.

  • @Jonathanálex pity you didn’t like the tips.

Show 2 more comments

0


Good as you want to make the user rewrite in the same house, if the note > 10, you can do the following, in this code snippet you can decrease your counter, this way it will go back to the same address:

scanf("%f %f",&aluno[contador].notaPhysics, &aluno[contador].notaMath);
if(aluno[contador].notaPhysics > 10.0 || aluno[contador].notaMath > 10.0){
    printf("Apenas notas até 10.\n");
    contador--;
}

But if you want to use Goto, I suggest you remove your RETORNO1 and RETORNO2 and also remove the Else.

  • Great! I’ll try it here

  • OK if using this method of decreasing the counter, remove the Goto

  • Thank you friend. Your contribution helped to solve my problem

Browser other questions tagged

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