Boolean function in C

Asked

Viewed 31 times

-2

College exercises.

Guys, I decided to make a function so you don’t have to write the same code every time I want to know if the user will continue or not the program.

What happens is that it seems that every time the function returns as true and my code continues again.

That was the function I created

bool continuarCodigo (char escolha, bool continuar){

printf("Deseja continuar o programa? S/N");
scanf("%c", &escolha);
fflush(stdin);
while (escolha != 's' && escolha != 'S' && escolha != 'n' && escolha != 'N'){
    printf("Opcao invalida, digite S/N");
    scanf("%c", &escolha);
    fflush(stdin);
}
if (escolha == 's' || escolha == 'S'){
    continuar = true;
} else if (escolha == 'n' || escolha == 'N'){
    continuar = false;
}

return continuar;

It even enters the last if to change the continue to false but the code continues the same way.

  • Add the code snippet that makes the call from that function, please.

  • I’ve got it, thank you very much for your attention :)

1 answer

0

Problem solved, after much break the head on how to print the boolean I was able to verify that it was working but was not changing the value of my variable in the main function, what I did was the following

continuar = continuarCodigo(escolha, continuar);

I declared the function inside my boolean variable in my code, there worked normally :)

  • Do not call the function within itself, this generates unnecessary recursion and can give stack overflow (see more here, here, here, here and here). Anyway, prefer a simple loop. And don’t use fflush(stdin), despite "working" in some cases, it is not portable and may not work in all environments (read here). Finally, a slightly better alternative would be: https://ideone.com/gEmhC5 - and read that

  • Damn it, man, thank you so much for the explanation! I’m a beginner so I didn’t quite understand the method of cleaning the buffer hehe but you can let me study to understand what you did Thank you very much :)

Browser other questions tagged

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