Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables inside C switch/case

Well, this is not actually a question..

I have just occasionally found out that there's an interesting way to declare local variables inside a switch/case block. Instead of using braces inside every case block, you can write:

switch (action) {
  int res;
  int value;
case ACTION_OPEN:
  res = open(...);
  ...
  break;
case  ...
}

So, I just wonder what C/C++ compilers besides gcc support this construction? It looks like a common fall-through. Any comments on this construction are welcome!

like image 439
zserge Avatar asked Nov 25 '10 14:11

zserge


People also ask

Can we declare variables inside switch-case in C?

Do not declare variables inside a switch statement before the first case label. According to the C Standard, 6.8.

Can you declare variables in a switch statement?

You can still declare variables in switch statements, you just have to put curly brackets around the code after the case label. Compare the two examples below. The first one generates an error. The second lets you compile and move on.

Why are variables not allowed to be used as the case values in a switch?

If the cases were allowed to contain variables, the compiler would have to emit code that first evaluates these expressions and then compares the switch value against more than one other value. If that was the case, a switch statement would be just a syntactically-sugarized version of a chain of if and else if .

Can I pass any type of variable to a switch statement in C?

1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.


2 Answers

The switch body is just a normal statement (in your case a compound statement, looking like { ... }) which can contain any crap. Including case labels.

This switch philosophy is abused by Duffs device.

Many people don't realize that even something like switch(0) ; is a valid statement (instead of having a compound statement, it has a null statement as body), although quite useless.

like image 158
Johannes Schaub - litb Avatar answered Sep 17 '22 23:09

Johannes Schaub - litb


Any standards-conforming C or C++ compiler will allow this . Even an old-fashioned (pre-ISO C99) C compiler will allow this, but only because the variable declarations are at the start of a block/compound statement (denoted by {}).

Note that what follows a switch is almost a normal statement, except for the possibility of case labels:

int main(int argc, char* argv[])
{
    switch (argc)
      default:
        puts("Hello, world!");

    return 0;
}

So in ANSI C89, it's the braces that do the magic here.

like image 36
Fred Foo Avatar answered Sep 20 '22 23:09

Fred Foo