My logic is:
if number is between 1 to 10, execute first case statement
if number is from 20 to 30, execute second case statement
is there a solution other than the one below?
case '1' ... '10':
case '20' ... '30':
The GCC compiler supports, as a language extension, case ranges like:
switch(i) {
case 0 ... 9: return true;
default: return false;
}
This language extension is also accepted by Clang/LLVM. So use it if you can afford restricting your code to GCC & Clang compilers.
See also this.
I have no idea why this extension was not included in C11 standard.
Notice also that GCC accepts computed or indirect goto
and labels as values. There are cases (in particular in
generated C code) where these features are useful. Examples could include some efficient bytecode interpreter. Some implementations of the Ocaml virtual machine are a good example.
void SwitchDemo(int value)
{
switch(value / 10)
{
case 0: ...; break; // 0 - 9
case 1: ...; break; // 10 - 19
...
}
}
or, specific to the question ranges:
void SwitchDemo(int value)
{
switch((value-1) / 10)
{
case 0: ...; break; // 1 - 10
case 1: ...; break; // 11 - 20
...
}
}
Option 1: use case 0
for 0-9
, case 1
for 11-20
and so on.
Option 2: use if
Option 3:
Another shabby way is using fall through cases like this:
#include <stdio.h>
int main(void) {
int i=1;
for(i=1;i<=25;i++)
{
switch(i)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
printf("%d is in between 1-10\n", i);
break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
printf("%d is in between 11-20\n", i);
break;
default:
printf("%d is above 20\n", i);
}
}
return 0;
}
Output:
1 is in between 1-10
2 is in between 1-10
3 is in between 1-10
4 is in between 1-10
5 is in between 1-10
6 is in between 1-10
7 is in between 1-10
8 is in between 1-10
9 is in between 1-10
10 is in between 1-10
11 is in between 11-20
12 is in between 11-20
13 is in between 11-20
14 is in between 11-20
15 is in between 11-20
16 is in between 11-20
17 is in between 11-20
18 is in between 11-20
19 is in between 11-20
20 is in between 11-20
21 is above 20
22 is above 20
23 is above 20
24 is above 20
25 is above 20
https://ideone.com/Cw6HDO
C doesn't support case values other than single integers (or integer-like things -- characters, enumeration values). So your options are:
case 1: case 2: case 3: ... case 10: do_something();
if
rather than case
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With