質問

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?

役に立ちましたか?

解決

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;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top