Am I able to add sets instead of numbers to "switch" statement? Like:
switch(number)
{
case 1<50: //if number is between 1 and 50
{
blah;
break;
}
case 50<100: //if number is between 50 and 100
{
blah;
break;
}
and so on.
Am I able to add sets instead of numbers to "switch" statement? Like:
switch(number)
{
case 1<50: //if number is between 1 and 50
{
blah;
break;
}
case 50<100: //if number is between 50 and 100
{
blah;
break;
}
and so on.
(Edit following comments below, acknowledgement given to user syam)
No. In C++ you can only switch on things that reduce to an integer. You'll need to build a function that computes integral results for 1 < 50 and 50 < 100 etc. and use switch(thatFunction(...)).
Or, if you don't need the follow-though idiom that a switch gives you (by the looks of your example, you don't), just use if
, else if
, else
.
Extract from below comments: 6.4.2-2 [stmt.switch] The condition shall be of integral type, enumeration type, or of a class type for which a single non-explicit conversion function to integral or enumeration type exists [...] the constant-expression shall be a converted constant expression (5.19) of the promoted type of the switch condition
1 < 50
is a boolean expression that gets a compile-time value of true
, and thus becomes 1
in an integer context. So you end up with two identical case
s in your switch
. Compile with high warning level - your compiler will surely complain.
Sadly not. You can use fall-through for a small set of discrete values:
case 1:
case 2:
blah;
break;
but for large ranges the only sensible option is if...else
.
For me, this works on my g++ (GCC) 4.7.2 20121109
#include <iostream>
using namespace std;
int main() {
switch(6) {
case 1 ... 5:
cout << "Between 1 and 5" << endl;
break;
case 6 ... 10:
cout << "Between 6 and 10" << endl;
break;
}
}
Thanks for stating in the comments that it's GCC's extenstion
Conditionals are not permitted as case statements, so your option is to use if / else statements.
You can't do that in C++. case
switches must be a constant that can be converted to an int
.
This is nicely discussed here.
A switch statement is useful when you have to use a single variable across many possible conditions. A switch statement works faster than an if-else
block by using a jump table. It requires constant integers when it makes the table. The reason expressions that dont evaluate to a fixed value are not allowed is to save from ambiguity.
case 1+a;
break;
case 5;
break;
Now what if a
is 4
. That will cause issues. If it doesnt use the jump table it wont be much useful than an if-else
block