Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Declaring a variable inside a switch statement

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?

like image 210
Noble-Surfer Avatar asked Apr 02 '26 20:04

Noble-Surfer


1 Answers

{ .. } creates a local scope, so your variable declaration won't be visible in the other one.

Add a declaration to each case with local scope, or, if you want to use the variable outside the switch statement, declare it before the switch.

like image 71
Karoly Horvath Avatar answered Apr 04 '26 09:04

Karoly Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!