I have a switch statement in my C++ code, and want to declare and use a variable inside a case of that statement. The variable will only be used inside the scope of that particular case.
switch(mode)
{
case abc:
...
struct commonData;
commonData = manager->getDataByIndex(this->Data.particularData);
int someInt = 1;
...
break;
case xyz:
...
commonData = Manager->getDataByIndex(this->Data.particularData);
break;
default:
...
break;
}
I tried simply declaring, initialising and using the variable (int someInt) just inside that case, but this gave me a few compile errors... Having come across this question on SO: Why can't variables be declared in a switch statement?, I tried doing what the answer suggested, and added {} to the case in question, so my switch now looks like this:
switch(mode)
{
case abc:
{
...
struct commonData;
commonData = manager->getDataByIndex(this->Data.particularData);
int someInt = 1;
...
break;
}
case xyz:
...
commonData = manager->getDataByIndex(this->Data.particularData);
break;
default:
...
break;
}
But I'm now getting compile errors that say: "undeclared identifier" on a variable (commonData) that is used inide the xyz case of the switch.
Having had a look into this- it seems that this variable is declared inside the abc case of the switch... So obviously, since I have added the {} to abc, by trying to use it outside abc, I am now trying to use it outside the scope of its declaration.
So why is it that I can't declare/ use someInt in the same way as commonData has been declared/ used without the need for the {} inside the case where it's declared?