C++ Is there a way to use the ‘&&’ operator for ‘switch’? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C++ Is there a way to use the ‘&&’ operator for ‘switch’?

Instead of using lots of “if’s” is there a way to use ‘switch’ and have the ‘&&’ operator?

5th Dec 2021, 5:10 PM
Bob Bob
8 Answers
+ 4
Bob Bob , this could be a possible solution: https://code.sololearn.com/cNxsaq380xZy/?ref=app
5th Dec 2021, 6:41 PM
Lothar
Lothar - avatar
+ 4
Vasiliy , that is really great, i did not realize that we can use a range here!
6th Dec 2021, 10:00 AM
Lothar
Lothar - avatar
+ 3
switch(age){ case 3 ... 5: cout << "Why are you even here?"; break; case 0 ... 2: cout << "Why?"; break; case 6 ... 8: cout << "Your not self aware" << endl; }
6th Dec 2021, 12:33 AM
Solo
Solo - avatar
+ 2
I think not, at least it is devoid of any logic for me. For what purpose would you like to use it?
5th Dec 2021, 5:52 PM
Solo
Solo - avatar
+ 1
https://code.sololearn.com/ceG9Kz5Jblee/?ref=app Take this as an example, you see there are lots of if statements can I change that?
5th Dec 2021, 11:57 PM
Bob Bob
+ 1
Like is there a way to make the switch statement go between numbers as the example above or is there not a shorter route?
6th Dec 2021, 12:01 AM
Bob Bob
+ 1
Bob Bob here is another way that looks pretty clean. #include <iostream> using namespace std; /* Please don't take any of these 'statements' offensive it is supposed to be a joke, thank you */ int main() { int age; cin >> age; string comments[] { "Why?", "Why are you even here?", "You're not self aware", "You're weird", "You're even weirder", "You're annoying", "You're rich", "You're old", "Do you know how you even got here?" }; int index = (age > 2) + (age > 5) + (age > 8) + (age > 12) + (age > 18) + (age > 47) + (age > 60) + (age > 99); cout << comments[index] << endl; return 0; }
6th Dec 2021, 8:34 PM
Brian
Brian - avatar
+ 1
Vasiliy Amazing, Perfect. Thank you! That makes things a lot easier for me now.
7th Dec 2021, 3:18 AM
Bob Bob