0

I'm using a switch statement that basically looks like this:

switch (command):
case '+':
   int key;
   scanf("%i", &key); 
   //do stuff
   break;
case '-':
   int key;
   scanf("%i", &key);
   //do stuff
   break;
....

It appears I'm not allowed to redeclare int key along the case ladder, even though they break as separate blocks of operation. I get compile error redeclaration of 'key' with no linkage so I'm just using key without typecasting it again. The program seems to run fine.

Is this acceptable? Is it safe?

user339946
  • 5,961
  • 9
  • 52
  • 97
  • 1
    Your code seems quite repetitve to me. Is it because you simplified for posting here or you actually have repeating code pieces which is a bad practice at the first place? – Seçkin Savaşçı Nov 24 '13 at 01:21

1 Answers1

4

It's not legal, and consequently it's not safe. But it's easy to fix. Just use blocks in your switch statement to limit the scope of your declarations:

switch (command):
case '+': {
   int key;
   scanf("%i", &key); 
   //do stuff
   break;
}
case '-': {
   int key;
   scanf("%i", &key);
   //do stuff
   break;
}
rici
  • 234,347
  • 28
  • 237
  • 341
  • Why not just declare `int key;` at the beginning of the function definition? – Fiddling Bits Nov 24 '13 at 03:48
  • 1
    @BitFiddlingCodeMonkey: That would work in this case, but in general different branches of the `switch` require different local variables. It's a question of style, really. I prefer to put local variables in the smallest possible scope. (And so does Google: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Local_Variables#Local_Variables ) – rici Nov 24 '13 at 04:04