+ 3

Can I do something like case>5 in the switch statement?

example: int num; cin>>num; switch(num); case 3:cout<<"xxx"; break; case 5:cout<<"yyy"; break; what if I want case =>5, or case <0? Can I do that? Or must I use the 'if' statement instead?

26th Dec 2016, 10:57 AM
Veii Xhen
Veii Xhen - avatar
6 ответов
+ 4
for this purpose it's better to use if else statement, but you may try to use default case in switch statement, write all conditions such as switch(x){ case1: break; case2: break; case3: break; case4: break; /* then use default case */ default: /* write here whatever you want for condition x>=5 */ } but for all x≠1,2,3,4 it will execute the default condition, so better option is to use if wale, switch works better where we need exact equating of values.
26th Dec 2016, 12:01 PM
Nikhil Dhama
Nikhil Dhama - avatar
+ 2
@Nikhil Dhama thanks!
26th Dec 2016, 1:08 PM
Veii Xhen
Veii Xhen - avatar
+ 2
@Valgeir Oh I understand it now! I thought you meant to say break is optional for all cases. Now I see...Thanks for your answer, and the helpful article!
28th Dec 2016, 3:00 AM
Veii Xhen
Veii Xhen - avatar
+ 1
@Valgeir I tried it on my code just now, and it didn't work. Seems like it needs a break statement for all cases.
27th Dec 2016, 1:53 AM
Veii Xhen
Veii Xhen - avatar
0
i am not sure about all languages but often you can put the cases right after each other that have the same result f.ex. case1: case2: case3: break; so it breaks for those three cases
26th Dec 2016, 3:45 PM
Valgeir Örn Kristjónsson
Valgeir Örn Kristjónsson - avatar
0
@Veii Xhen really? aren't you using c++? you can see in this article how it can be used https://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm
27th Dec 2016, 9:59 PM
Valgeir Örn Kristjónsson
Valgeir Örn Kristjónsson - avatar