ID:1639204
 
Hey guys,

After having learned DM fairly well, I decided to learn C++ and see where it takes me. I'm working on switch statements right now and have the following question:
Can I test a condition under case rather than a single value? For example:

something like...
    switch ( x ) {
case x < 7:
cout << "Too few!" << endl;
break;
}


...instead of...
    switch ( x ) {
case 7:
cout << "Too few!" << endl;
break;
}


Is this possible? I'd really appreciate your suggestions. =D
According to Stack Overflow, you cannot test for conditions in a case statement—the value must be constant. You'll have to use an if else chain instead.
Gotcha - I was hoping that wasn't the case, but I guess I have no other options. Thanks for the answer!
Ralf, think of it this way.

switch(input("bla bla bla") in list ("1", "2", "3"))
if("1")
//do something

if("2")
//do something

if(x > 7)
//doesnt do something


They work fairly close to each other.

Like Andrew said, you can use an if statement to check if x is less than 7 instead of using a switch statement. You don't need to get too fancy. Cut to the chase.

if(x < 7)
cout << "Too few!" << endl;
//no break needed unless you're in some for loop or something.


Good luck. And remember. Once you've learned 1 language.. You've essentially learned all other languages. I learn new languages easy as pie. In fact, I haven't even touched C++ a day in my life. Yet, I can already tell you from my experience with C# and PHP that switch doesn't work that way. lol.
if(x < 7) is the same as if(0) or if(1) depending on the value of x. This goes for both the switch() and normal conditional statements.