
A switch-case structure performs a complex decision in your code, similar to a cascade of if else-if else statements. The structure works like a comparison as a whole, acting upon single values or variables. But its construction need not lack expressions.
In my books, I describe the switch statement like this:
Unlike an if statement, switch eats only a single value.
And I describe case like this:
A case statement shows a single value . . . followed by a colon.
It’s true that switch and case operate on single values, either a variable, constant, or literal value. But they can also work with expressions. The key is that the expression must result in a single value, as this code demonstrates:
2020_08_08-Lesson-a
#include <stdio.h>
int main()
{
switch( 4-2 )
{
case 4:
puts("The answer is 4");
break;
case 3:
puts("The answer is 3");
break;
case 2:
puts("The answer is 2");
break;
case 1:
puts("The answer is 1");
break;
case 0:
puts("The answer is 0");
break;
default:
puts("I don't know!");
}
return(0);
}
At Line 5, the switch keyword’s parentheses feature an expression, ( 4-3 ). It’s not a comparison; the comparison happens between the result of the switch expression and what follows the case keywords in the structure. The results of the expression is 2 and the case 2: statement’s (starting at Line 13) are executed.
As with switch, the case keywords can also sport an expression, providing it returns a single value:
2020_08_08-Lesson-b
#include <stdio.h>
int main()
{
switch( 4-2 )
{
case (4-0):
puts("The answer is 4");
break;
case (4-1):
puts("The answer is 3");
break;
case (4-2):
puts("The answer is 2");
break;
case (4-3):
puts("The answer is 1");
break;
case (4-4):
puts("The answer is 0");
break;
default:
puts("I don't know!");
}
return(0);
}
Of course, this example is pedantic; obviously 4-2 matches 4-2. Still, it’s the result that’s compared, not the literal expression.
What happens when you use a comparison in a switch statement? Oo! Let’s find out:
2020_08_08-Lesson-c
#include <stdio.h>
int main()
{
int a,b;
a = 10;
b = -10;
switch( a > b )
{
case 1:
printf("%d is greater than %d\n",a,b);
break;
case 0:
printf("%d is not greater than %d\n",a,b);
break;
default:
puts("I'm not sure what's going on");
}
return(0);
}
This code compiles with a warning. The switch statement’s expression at Line 10 is a “boolean.” Still, this warning doesn’t stop the program from being built. Here’s the output:
10 is greater than -10
You can suppress the warning by casting the switch statement like this:
switch( (int)(a > b) )
Still it’s easier to use an if statement instead. After all, it’s the right tool for the job.