I have recently begun studying C just for the fun of it and I decided to have a go at creating a menu system, but I'm having an issue with what I think is fall through.
#include <stdio.h>
int main (void)
{
int x, y, z;
start:
printf ("Menu 1 -- Please select a number.\n");
printf ("1\n");
printf ("2\n");
printf ("Enter selection: ");
scanf ("%i", &x);
getchar();
if (x == 1) {
x_one:
printf ("1.\n");
printf ("Menu 2 -- Please select a number.\n");
printf ("1\n");
printf ("2\n");
printf ("3 -- Go back.\n");
printf ("Enter selection: ");
scanf ("%i", &y);
getchar();
if (y == 1) {
y_one_one:
printf ("1-1.\n");
printf ("Menu 3 -- Please select a number.\n");
printf ("1\n");
printf ("2\n");
printf ("3 -- Go back.\n");
printf ("Enter selection: ");
scanf ("%i", &z);
getchar();
if (z == 1 || z == 2)
printf ("You selected %i.\n", z);
if (z == 3)
goto x_one;
else if (z > 1 && z < 3)
goto y_one_one;
}
if (y == 2) {
/* mostly the same as "if (y == 1)". */
}
if (y == 3)
goto start;
else {
printf ("Please enter a valid selection.\n");
goto x_one;
}
}
if (x == 2) {
/* Mostly the same as "if (x == 1)". */
}
else if (z > 1 && z < 2)
goto start;
return 0;
}
The issue is once I have reached the third menu, the program will print out the string of the selected number, but instead of terminating itself it will either display the third menu or go back to the second menu, and it will do this regardless of what number I input.
I've only been studying C for about two weeks and I don't quite have a proper understanding on how nested if statements work, if I could please get an explanation of what's causing this unexpected behavior and how to correct it that would be greatly appreciated, thank you.
I am using GCC 5.1.0 through TDM-GCC-64 on Windows 10.
Aucun commentaire:
Enregistrer un commentaire