+ 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?
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.
+ 2
@Nikhil Dhama thanks!
+ 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!
+ 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.
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
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