Expected Expression Error

You tried to declare a variable after a ‘case’ statement and it showed an error. If that’s the reason you are here, then read on. This must actually be surprising to most people familiar with C++ programming because C++ allows us to declare variables almost anywhere in the program. In fact, declaring them close the first use is actually a good practice. So why can’t you declare variables after a case label in a switch statement?  

Let’s start with an example:

switch (val) 
{ 
    case VAL: 
        int newVal = 42; 
        break;
    case ANOTHER_VAL: 
        ...
        break;
    default:
        break;
}

The above gives the following error:

initialization of ‘newVal’ is skipped by ‘case’ label

This is actually not just limited to C++, it happens in other languages as well. The reason for this is that ‘case’ statements are only ‘labels’. This means the compiler will interpret this as a jump directly to the label. The problem here is the one of scope. The curly brackets define the scope as everything inside the ‘switch’ statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization. The correct way to handle this is to define a scope specific to that case statement and define your variable within it. The correction is as given below:

switch (val)
{ 
    case VAL: 
    {
        int newVal = 42; 
        break;
    }
    case ANOTHER_VAL: 
        ...
        break;
    default:
        break;
}

————————————————————————————————-

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s