Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About switch{} case in C?

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.

like image 584
ipkiss Avatar asked Mar 03 '11 10:03

ipkiss


People also ask

What is a switch case in C?

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.

What is the used of 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.


2 Answers

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.

like image 118
unwind Avatar answered Sep 19 '22 02:09

unwind


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.

like image 30
log0 Avatar answered Sep 20 '22 02:09

log0