J. Smith
J. Smith

Reputation: 143

How can I make a case statement based on an iterable?

I want to make a case statement based on an iterable, but I understand that the case expression must be a constant. What is a workaround for this?

I tried the below code, but it still does not work.

#include <iostream>
using std::cout;
using namespace std;

int main()
{
    int i = 0;
    while( i >= 0)
    {
        const int z = i;
        cout << "Enter a number other than " << z << "!\n";
        int choice;
        cin >> choice;
        switch(choice){
            case z: cout << "Hey! you weren't supposed to enter "<< z <<"!"; return 0; break;
            default: if(i==10)
                    {
                        cout << "Wow, you're more patient then I am, you win."; return 0;
                    }
                    break;
        }
        i++;
    }

}

Upvotes: 2

Views: 158

Answers (2)

dg77
dg77

Reputation: 1

When a switch statement is encountered, the execution continues from from the corresponding case block all the way to the end of the switch statement unless a break is encountered. Therefore the switch statement is closer in "spirit" with an goto statement and not nested ifs. The implementation is also different and it is done using assembly branch tables as explained here.

Why can't I use non-integral types with switch

Therefore, like Daniel Trugman said you need to use nested if statements.

Upvotes: 0

Daniel Trugman
Daniel Trugman

Reputation: 8501

case requires constant integral values known at compile-time.

So you'll have to use if-s:

if (choice == z) {
  cout << "Hey! you weren't supposed to enter "<< z <<"!";
  return 0;
} else if (i == 10) {
  cout << "Wow, you're more patient then I am, you win.";
  return 0;
}

Upvotes: 6

Related Questions