سؤال

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