+ 1

Can we use operators in switch statement??

eg; switch(any) { case 9&&10&&11: cout<<" some thing" ; break; }

24th Jan 2018, 1:18 PM
Mubarak Hussain
Mubarak Hussain - avatar
7 Answers
+ 16
Yes.. U can use but the case should not repeat... Like we know by using logical operators only 0 & 1 value can be obtained so u can create max two cases.. for eg:- int a=1; switch (a){ case 1&&1: cout<<"yes"; break; case 1&&0: cout<<"no"; break; } will output :- yes.. but if u use cases giving same answer it will generate error... for eg:- int a=1; switch (a){ case 1&&1: cout<<"yes"; break; case 1||0: cout<<"no"; break; } this will generate error as both cases have value 1
24th Jan 2018, 2:14 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 14
@mubarak int a; cin>>a;
25th Jan 2018, 7:45 AM
🌛DT🌜
🌛DT🌜 - avatar
+ 11
@Mubarak if the case value repeats it will give execution error.... "duplicate error"...😊 @Anderson U cannot use x, y variable... only constants are used... but u can use it by making x & y constants.... like this...:- 👇 int main() { int a=1; int const x=2; int const y=3; switch (a){ case (x<y): cout<<"yes"; break; case (x>y): cout<<"no"; break; } return 0; } // outputs:- yes
24th Jan 2018, 7:30 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 2
@DT is there any way to write case (x <= y): statements? Because it was actually a compiling error if it was written as shown... The reason I wanted to do this it's because it would look messy to have a bunch of 'if' statements...
24th Jan 2018, 2:33 PM
Anderson Chong
Anderson Chong - avatar
+ 1
if it repeats, it will give the same value or execution error??
24th Jan 2018, 2:32 PM
Mubarak Hussain
Mubarak Hussain - avatar
0
@DT but i want a value from user,
24th Jan 2018, 7:57 PM
Mubarak Hussain
Mubarak Hussain - avatar
0
@DT thanks a lot!
25th Jan 2018, 9:06 AM
Anderson Chong
Anderson Chong - avatar