A generalization of Switch

Switch says if variable x is v1 then do this, v2: do that and so on.
Is there a simple generalization that expresses: if x is in range [v1,v2] do something, if in [v3,v4] do something, if in [v5, v6]...

I can use if statements, but if can also be used in place of normal switch statements; Switch is a nice syntactic sugar.

Is there a nice way to do ranges?
Well, you could list all the values in the range ...
1
2
3
4
5
6
7
8
9
10
11
12
switch (x)
{
case 1:
case 2:
case 3:
	// do something
	break;
case 4:
case 5:
	// do something else
	break;
}

... but that is only useful if the ranges are small, otherwise it's better to use if statements.
There is no facility in the language to handle ranges, so you have to use if/then

Note that if the ranges partition the number space then you only need to check one value. For example, a common problem on these boards is converting a numeric grade to a letter grade:
1
2
3
4
5
if (num < 60) grade = 'F';
else if (num <70) grade = 'D';
else if (num < 80) grade = 'C';
else if (num < 90) grade = 'B';
else grade = 'A';

In some cases it might also be desirable to encode the ranges in data and use a little loop to find the appropriate range, then use a case statement to select what to do.
Here's another idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

int main()
{
    int a;

    std::cin >> a;

    switch ( (a >=  0 && a < 10)     +
             (a >= 10 && a < 20) * 2 +
             (a >= 20 && a < 50) * 3 )
    {
    case 1:
        std::cout <<  "[0, 10)" << std::endl;
        break;
    case 2:
        std::cout << "[10, 20)" << std::endl;
        break;
    case 3:
        std::cout << "[20, 50)" << std::endl;
        break;
    default:
        std::cout << "(-oo, 0) U [50, +oo)" << std::endl;
    }
}

I'd prefer if statements over this though.
I do like your solution m4ster r0shi :)
Topic archived. No new replies allowed.