switch‐case - chunhualiao/public-docs GitHub Wiki
no inner indentation
Yes, that version of the code will work just fine — even though all the statements are at the same indentation level — because:
case
labels
✅ No variable declarations inside In your example:
switch(ch){
case '\n':
foundNewLine = true;
break;
case '\t':
foundHorizontalTab = true;
break;
}
You're only executing statements, not declaring new variables. The compiler has no issue with this because:
- Control flow (
switch
andcase
) does not violate any rules when simply executing statements like assignments or function calls. - There are no jumps into the middle of variable initializations, which is what causes errors when variables are declared.
🔍 Indentation vs. Syntax
- Indentation is purely for human readability.
- The compiler doesn’t care if everything is left-aligned, indented nicely, or in a single line — it only parses tokens and braces, not whitespace (outside of preprocessing).
✅ So this works because:
- You're not declaring any variables inside the
case
blocks. - You're using simple, executable statements, which are allowed without additional scope
{}
.
If you later need to declare a variable inside one of those case
blocks, then yes — you'll need to wrap that case
block in braces {}
as shown in the previous answer.
jum to case label
The error you're seeing:
translator_processed_files/rose_fileFilter.C:95:14: error: jump to case label
95 | case '\t':
| ^~~~
is caused by declaring variables inside a switch
case without proper scoping. C++ does not allow variable declarations directly inside case
labels without a compound statement ({}
block) to scope them. This is because control flow can "jump" into the middle of a declaration, which would violate the language's rules.
Problem Code:
switch(ch){
case '\n':
int testVar19 = 42; // <-- error-prone
foundNewLine = true;
int anotherTestVar19 = 24;
int testVar20 = 42;
break;
case '\t':
int testVar21 = 42; // <-- also problematic
foundHorizontalTab = true;
int anotherTestVar21 = 24;
int testVar22 = 42;
break;
}
✅ Corrected Version:
Wrap the code under each case
in its own block {}
to define a local scope:
switch(ch){
case '\n': {
int testVar19 = 42;
foundNewLine = true;
int anotherTestVar19 = 24;
int testVar20 = 42;
break;
}
case '\t': {
int testVar21 = 42;
foundHorizontalTab = true;
int anotherTestVar21 = 24;
int testVar22 = 42;
break;
}
}
Why This Happens:
The C++ standard prohibits jumping past the initialization of a variable with non-trivial constructor/destructor (which applies even to trivial types like int
for safety reasons). Declaring variables directly in a case
label without a block would allow control to "jump" over their initialization.
Fix Summary:
Wrap each case
body in curly braces { ... }
if you're declaring variables inside it.