So, i have this code:
#include <stdio.h>
void menu_loop(int run) {
if (run == 0) {
printf("bad\n");
menu();
}
else
printf("good");
}
int check_menu(int menu1) {
if (menu1 > 3 || menu1 < 0)
return 0;
else
return 1;
}
int menu() {
int choice;
printf("----MENU----\n0 -> Exit\n1 -> Prime time\n2 -> Calander calculating\n3 -> Matrix printing\n");
scanf_s("%d", &choice);
int check2 = check_menu(choice);
menu_loop(check2);
}
void main() {
menu();
}
what i need to do is whenever check_menu returns a 0 then i need to have a certein variable that starts at 0 go up by 1. everytime i try this i find that the value gets reinitialized to 0 since im initializing it inside the function. thanks in advance!
CodePudding user response:
Returning an error code from a function in case something bad has happened is a common practice in C as it doesn't has a concept of throwing an exception as in more high level languages. I recommend you defining a macro to be more explicit and use a loop instead of recursion.
#include <stdio.h>
#define INVALID_CHOICE_ERR 1
int check_menu(int menu1)
{
if (menu1 > 3 || menu1 < 0)
return INVALID_CHOICE_ERR;
else
return 0;
}
int menu()
{
int choice;
do {
printf("----MENU----\n0 -> Exit\n1 -> Prime time\n2 -> Calander calculating\n3 -> Matrix printing\n");
scanf_s("%d", &choice);
} while (check_menu(choice) == INVALID_CHOICE_ERR);
// Now that a valid choice has been selected, you can use it
}
void main()
{
menu();
}
Or you can get rid of the macro and function by simplifying the while loop
while (choice > 3 || choice < 0);
Also I recommend you reading about the disadvantages of scanf()
Disadvantages of scanf