The GNU case range extension allows case ranges in switch statements:
switch (value) {
case 1 ... 8:
printf(\"Hello, 1 to 8\\n\");
break;
I would use an if
statement:
if (value >=1 && value <= 8) {
printf("Hello, 1 to 8\n");
} else {
printf("Hello, default\n");
}
You can then add extra else if
statements if more ranges are required,
Alternatively, since the numbers are adjacent to each other, you can do a manual optimization of the switch-case.
typedef void(*func_t)(void);
#define CASES_N 9
void func0 (void)
{
printf("Hello, 0\n");
}
void func1 (void)
{
printf("Hello, 1 to 8\n");
}
static const func_t execute [CASES_N] =
{
&func0,
&func1,
&func1,
&func1,
&func1,
&func1,
&func1,
&func1,
&func1
};
int main()
{
if(what < CASES_N)
{
execute[what]();
}
else
{
printf("Hello, default\n");
}
}
This code is basically the same as a compiler-optimized switch-statement.
switch(value)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
printf("Hello, 1 to 8\n");
break;
default:
printf("Hello, default\n");
break;
}
EDIT: To answer the comment.
If you have too many cases, then You might want to consider replacing the switch-case with if-else constructs. It can be much cleaner, concise & readable.
if (value >=1 && value <= 8)
{
printf("Hello, 1 to 8\n");
}
else
{
printf("Hello, default\n");
}
If long long range you could do, a bit dirty but,
switch(what) {
case 1:
/* do 1 */
break;
case 2:
/* do 2 */
break;
default:
if (what > 31 && what < 127) {
/* do 32 to 126 */
}
}
The best would probably be to remove the switch for an if all together.
Be extremely strict with nesting. If you want the switch, for some reason, then better then the above would be:
if (value > 31 && value < 127) {
/* Do something */
} else {
switch (value) {
case 1:
...
}
}
Ach, sorry for edit again. This would be cleaner.
if (value > 31 && value < 127) {
/* Do something */
} else if (value > 127 && value < 178) {
} else if ( ...
}
switch (value) {
case 1:
...
}