Home > Back-end >  One case of the menu conditioned by other
One case of the menu conditioned by other

Time:12-09

I have a c program with a menu of 9 cases. I need that the case 7 is only executed if the case 3 has been used before case 7. How can I do it? Thanks.

I don't know how to use a case in an "if".

CodePudding user response:

Here's an example of using an if inside a case statement:

case 7:
{
    if (previous_selection == 3)
    {
        Do_Operation();
    }
}
break;

This one of many possible solutions, there are others.

CodePudding user response:

You have to flag somehow that case 3 has been executed. For example, with a bool variable, setting it as part of the case 3 block of instructions, and checking it as part of the case 7 block of instructions.

[Demo]

#include <iostream>  // cout

int main() {
    bool case_3_already_used{ false };
    for (auto index : { 7, 6, 5, 3, 2, 1, 8, 7, 9 }) {
        switch (index) {
            case 0: { std::cout << "0\n"; break; }
            case 1: { std::cout << "1\n"; break; }
            case 2: { std::cout << "2\n"; break; }
            case 3: {
                std::cout << "3\n";
                case_3_already_used = true;
                break;
            }
            case 4: { std::cout << "4\n"; break; }
            case 5: { std::cout << "5\n"; break; }
            case 6: { std::cout << "6\n"; break; }
            case 7: { 
                if (case_3_already_used) {
                    std::cout << "7\n";
                } else {
                    std::cout << "Cannot execute case 7 since case 3 has not been executed yet.\n";
                }
                break;
            }
            case 8: { std::cout << "8\n"; break; }
            case 9: { std::cout << "9\n"; break; }
            default: break;
        }
    }
}

// Outputs:
//
//   Cannot execute case 7 since case 3 has not been executed yet.
//   6
//   5
//   3
//   2
//   1
//   8
//   7
//   9

Now, were the switch logic in a separate function, you would need to keep the state of that boolean variable between different calls. A way to do that would be to mark the flag as static.

[Demo]

  • Related