i was working on an educationary project to study C where specific labels include code to that specific topic being studied. However, at the end of each code block i want the compiler to ask if the user wants to exit or countine from beginning:
void main(void)
{
beginning:
printf("goto : \n 1) pointers \n 2) classes \n 3) \n 4) \n 5) \n ");
scanf_s("%d", &input);
switch (input)
{
case 1:
goto pointers;
case 2:
goto classes;
case 3:
case 4:
case 5:
default:
printf("wrong try again \n");
goto beginning;
}
pointers:
.....
classes:
......
}
the code to check what the user wants:
do {
printf("1 for exit and 2 for return menu \n");
scanf_s("%d", &reserved);
if (reserved == 2) { goto beginning; }
else if (reserved == 1) { exit; }
else { printf("wrong number, put a valid one you little..!"); }
} while (reserved != 1 && reserved != 2);
i tried to turn it to a function but the problem is labels are defined putside of main function so i want to just make the compiler put my function once it is called and not evaulate it from the beginning.
CodePudding user response:
The proper way to structure the code would be (pseudocode follows):
Do
PrintPrompt()
input = ReadInput()
switch (input)
case 1: DoFirstThing()
case 2: DoSecondThing()
...
default: PrintError()
While (UserWantsToContinue())
There's really no justification to using goto here (or almost anywhere, see answers to this question). For the canonical thesis go here.
