I am reading some text in C language
. The text says that switch{} case
can only accept integer type.
I am just curious about why switch{} case
does not accept other types such as float or string. Are there any reasons behind this?
Thanks a lot.
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
The switch case in java executes one statement from multiple ones. Thus, it is like an if-else-if ladder statement. It works with a lot of data types. The switch statement is used to test the equality of a variable against several values specified in the test cases.
The classical reason is probably that for integer-valued "decision expressions", it's possible to do very nice optimizations.
Basically, you can map the list of case-statements to a table containing addresses, and then directly jump based on the value. Obviously, for floats and strings that doesn't work.
In GCC, you can do this by hand using some extensions like so:
const char * digit_name(int d)
{
const void * handlers[] = { &&zero, &&one, &&two, &&three, &&four,
&&five, &&six, &&seven, &&eight, &&nine };
goto *handlers[d]; /* Assumes d is in range 0..9. */
zero: return "zero";
one: return "one";
two: return "two";
three: return "three";
four: return "four";
five: return "five";
six: return "six";
seven: return "seven";
eight: return "eight";
nine: return "nine";
return NULL;
}
This is in general called a "computed goto", and it should be clear how a switch
can basically be compiled down to something very similar. Tight definition of the switched-on expression helps, such as using an enum
.
Also, C doesn't really have much of a concept of strings at the language level.
The language philosophy of C is what you see is what you get. There is no hidden mechanisms. This is actually one of the great strength of the language.
Switching on integer involves a branching as expected, while comparing on float and string would have a hidden cost.
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