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’ labelThis 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; }
————————————————————————————————-
Thanks for this. I kept looking at my switch-case code and could not determine why I was getting an error just initializing an int. I’m a Java developer and I did C a long time ago. I showed your two snippets to my wife (non-dev) and asked her to show me “any” difference in your two snippets. She said those curly-brace things, LOL.