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