sa*****@yahoo.co.in writes:
In the following code, i have a common action for three switch cases,
is there any other better way to write the three values in a single
case?
#include <stdio.h>
int main()
{
int i = 1;
switch(i)
{
case 2: printf("before...\n");
break;
case 4:
case 5:
case 6: printf("in...\n");
break;
case 7: printf("out...\n");
break;
}
return(0);
}
No, there's no standard syntax for specifying a range in a case
statement (yes, it might be nice if there were). For only 3 cases,
enumerating each case is probably the best approach. For a larger
range, say a few hundred cases, you can just use a series of if/else
statements. The following is equivalent to your program, but can
easily be modified to cover larger ranges:
#include <stdio.h>
int main(void)
{
int i = 1;
if (i == 2) {
printf("before...\n");
}
else if (i >= 4 && i <= 6) {
printf("in...\n");
}
else if (i == 7) {
printf("out...\n");
}
return 0;
}
If you have a combination of individual values and large ranges, you
can even combine a switch statement with an if statement:
#include <stdio.h>
int main(void)
{
int i = 1;
switch (i) {
case 2:
printf("before...\n");
break;
case 7:
printf("out...\n");
break;
default:
if (i >= 4 && i <= 6) {
printf("in...\n");
}
break;
}
return 0;
}
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.