문제

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