Can we use a condition in switch...case? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can we use a condition in switch...case?

It's like switch(x) { case (x>0) cout<<"Jump"<<endl; break; ...

21st Dec 2016, 8:30 PM
Rakki
Rakki - avatar
3 Answers
+ 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.
22nd Dec 2016, 1:27 AM
Thomas Stone
Thomas Stone - avatar
+ 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 :)
1st Feb 2017, 3:20 AM
Zeke Williams
Zeke Williams - avatar
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.
21st Dec 2016, 10:16 PM
Nathan Smith
Nathan Smith - avatar