+ 3
Can we use a condition in switch...case?
It's like switch(x) { case (x>0) cout<<"Jump"<<endl; break; ...
3 Réponses
+ 2
You cannot in C++ unless x is declared as const (which makes that code pretty much useless in 99% of circumstances). This is because case requires a constant expression. Which is to say, it's value has to be determined at compile time.
+ 1
One of the things I have learned is that you can use enumerations in a switch case. This might be a little complicated, but here is how you would use it:
enumeration class Conditions {
Jump,
Not_Jump,
Run,
Fly,
Default
};
Conditions ReturnCondtions(int x) {
if (x > 0)
return Conditions::Jump;
else if(x > 0)
return Conditions::Not_jump;
else if(x == 0)
return Conditions::Run;
else if(x >= 100)
return Conditions::Fly;
else
return Conditions::Default;
}
int main() {
int x = 15;
switch (ReturnConditions(x)) {
case Conditions::Jump:
cout << "Jump!" << endl;
break;
case Conditions::Not_jump:
cout << "Not jumping." << endl;
break;
etc...
}
This is usually used in more complicated code though, but I thought I'd at least present to anyone who is interested in learning more :)
0
Under normal circumstances you can only use integer values for switch statements; though there are a number of ways to finiggle with the specifics of this because any function that returns an integer, a character interpreted as an integer and the like could all be used. So you could simply typecast true and false into 1 and 0 respectively, using them as your cases.
Best of luck.