Larger than and less than in C switch statement
A switch-less and if-else-less method:
#include <stdio.h>
int main(void)
{
int a=0, i;
struct {
int value;
const char *description;
} list[] = {
{ -999, "hugely negative" },
{ -99, "very negative" },
{ 0, "negative" },
{ 1, "zero" },
{ 100, "positive" },
{ 1000, "very positive" },
{ 1001, "hugely positive" }
};
printf("please enter a number : \n");
scanf("%i",&a);
for (i=0; i<6 && a>=list[i].value; i++) ;
printf ("%s\n", list[i].description);
return 0;
}
The for-loop contains no code (there is just an empty statement ;
) but it still runs over the array with values and exits when the entered value a
is equal to or larger than the value
element in the array. At that point, i
holds the index value for the description
to print.
There is no clean way to solve this with switch, as cases need to be integral types. Have a look at if-else if-else.
If you are using gcc, you have "luck" because it supports exactly what you want by using a language extension:
#include <limits.h>
...
switch(a)
{
case 1000 ... INT_MAX: // note: cannot omit the space between 1000 and ...
printf("hugely positive");
break;
case 100 ... 999:
printf("very positive");
break;
...
}
This is non-standard though, and other compilers will not understand your code. It's often mentioned that you should write your programs only using standard features ("portability").
So consider using the "streamlined" if-elseif-else
construct:
if (a >= 1000)
{
printf("hugely positive");
}
else if (a >= 100)
{
printf("very positive");
}
else if ...
...
else // might put a helpful comment here, like "a <= -1000"
{
printf("hugely negative");
}
(a>1000)
evaluates to either 1 [true] or 0 [false].
Compile and you will get the error:
test_15.c:12: error: case label does not reduce to an integer constant
This means, you have to use an integer constant
value for the case
labels. An If-else if-else
loop should work just fine for this case.