+ 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?
9 odpowiedzi
+ 4
Bob Bob ,
this could be a possible solution:
https://code.sololearn.com/cNxsaq380xZy/?ref=app
+ 4
Vasiliy ,
that is really great, i did not realize that we can use a range here!
+ 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;
}
+ 2
I think not, at least it is devoid of any logic for me.
For what purpose would you like to use it?
+ 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?
+ 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?
+ 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;
}
+ 1
Vasiliy Amazing, Perfect. Thank you! That makes things a lot easier for me now.