Choco Fernandez Choco Fernandez - 2 months ago 16
C Question

Nested switch: Outer switch automatically executes the second case after exiting inner switch

I'm trying to create a menu for my RPG-esque program, it consists of the Main Menu(outer switch) and Inventory Menu(inner switch), my problem is when I exit from my inner switch, the next case of the outer switch(dispChar()) executes.
Here is the code

do{
printf("\n(i)Open Inventory\t(c)View Character\t(p)[Mini-Game]Hit the Chest!\t(z)Exit\n");
mainMenu = getch();
switch (mainMenu)
{
case 'i':
OpenInventory(&inv);
do
{
printf("\n(a)Equip Weapon\t(b)Equip Helmet\t(c)Equip Suit\t(d)Equip Gloves\t(e)Equip Boots\t(z)Back\n");
op2 = getch();
switch(op2)
{
case 'a':
equipWep(&chara, &inv);
break;
case 'b':
equipHelm(&chara, &inv);
break;
case 'c':
equipSuit(&chara, &inv);
break;
case 'd':
equipGloves(&chara, &inv);
break;
case 'e':
equipBoots(&chara, &inv);
break;
}
}while(op2 != 'z');
case 'c':
dispChar(chara);
break;
case 'p':
if(chara.wep.damage == 0)
{
printf("No weapon equiped!");
}else
{
grind(&chara);
break;
}


}
}while(mainMenu != 'z');


Here are some of my functions:

void OpenInventory(inventory inv[size])
{
dispWep(inv);
dispHelm(inv);
dispSuit(inv);
dispGloves(inv);
dispBoots(inv);
}

void dispChar(character chara)
{
printf("\nName:%s\nSex:%c\nWeapon:%s\nHelmet:%s\nSuit:%s\nGloves:%s\nBoots:%s\n",chara.charName, chara.charGen, chara.wep.weaponName,chara.helm,chara.sut,chara.glabs,chara.buts);
}


If the rest of my code is needed, please let me know.

Answer

If you don't want the outer switch statement to continue to execute rest of the cases, add a break; after the end of the inner switch and before the next case statement of the outer switch statement.

switch (mainMenu)
{
    case 'i':
        OpenInventory(&inv);
        do
        {
           printf("\n(a)Equip Weapon\t(b)Equip Helmet\t(c)Equip Suit\t(d)Equip Gloves\t(e)Equip Boots\t(z)Back\n");
           op2 = getch();
           switch(op2)
           {
              ...
           }
        } while(op2 != 'z');

        // Add this
        break;

    case 'c':
Comments