0

Is it bad practice to initialize variables inside a specific case of a switch?

I have quite a few variables that is only relevant for one of my cases, and can't seem to find any info on this.

Thanks :)

kensing
  • 95
  • 1
  • 1
  • 8

3 Answers3

4

Why not only declare them for the case where they're relevant?

switch (something)
{
case 1:
    do_something();
    break;

case 2:
  {
    int x = 12;
    do_something_else(x);
    break;
  }
}

Don't miss out the curly braces used in case 2: to create a sub-scope. Thus, variable x is local to case 2

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
2

In general, I would say if one of your cases is complex enough that it requires it's own variables that aren't used elsewhere, it should probably actually become it's own function.

Brandon Yates
  • 2,022
  • 3
  • 22
  • 33
-1

If you have something like this:

 class X { X() {...} /* and other stuff */ };

 switch(a)
 {
    case 1:
       X x;
       ... using x here .. 
       break;
    case 2:
       ... 
       break; 
  .... 
 }

then x will be destroyed at the end of the switch brace. Which won't be a great idea, since for cases other than 1, it won't have been initialized. [This example won't compile, because the compiler DETECTS that this will happen, and gives an error!]

So use braces to wrap it:

    case 1:
       {
         X x;
         ... using x here .. 
       }
       break;
    case 2:
       ... 
       break; 
  .... 

Now X is destroyed before the break, which is fine.

Other than this part, there's nothing wrong with having local variables in a specific case. In fact, I'd say it's a GOOD thing [but perhaps better is to write a small function!]

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Your first example doesn't compile (and not just because it needs `public: X()`). `initialization of 'x' is skipped by 'case' label`. – RichieHindle May 13 '13 at 15:49
  • Yes, so the compiler will figure out that the constructor isn't being called - although I had a feeling (at least some) compilers only gave a warning for it. Either way, using braces solves the problem and avoids other interesting issues (e.g make it an initalized `int` and use it in `case 2` and see what happens). – Mats Petersson May 13 '13 at 15:53
  • 2
    I did, and I got the same compiler error. The question is about what happens when you declare the variable *outside* the `switch`. Your answer is correct in its advice, but your first example is bogus. (Also, the question is for C, not C++.) – RichieHindle May 13 '13 at 15:56
  • Ok, I've edited the post to say "you can't actually compile this, but it would be bad if you could" sort of thing. – Mats Petersson May 13 '13 at 16:02