zserge
zserge

Reputation: 2262

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!

Upvotes: 7

Views: 6135

Answers (4)

Jens Gustedt
Jens Gustedt

Reputation: 78923

Strictly spoken, the case that you present with int is allowed in all three languages, but for different reasons.

C allows jumping across the definition of any local variable (arithmetic, struct, union, array...) in all cases (for C89) and in all cases but one (for C99). The exception for C99 are variable length arrays.

C++ allows this only for data types that don't have a constructor or destructor, often referred to as POD.

So if you have a type T instead of int in your example in C89 this is always valid, and in C99 and C++ it depends on the type T whether or not this is correct.

In any case, all of this easily leads to uninitialized variables, so better don't do it if you can avoid it.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363607

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.

Upvotes: 1

Jack
Jack

Reputation: 133587

I think that C99 allows to declare variable (almost) wherever you want inside blocks, so that behavior should be considered legal.. and I don't see any actual risk since it's just a declaration.

Upvotes: -1

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507015

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.

Upvotes: 3

Related Questions