C语言switch语句语法疑问求助(GCC/Ubuntu 16.04环境)
Hey there! Let's clear up those two switch statement questions you have—they’re common points of confusion, so you’re not alone here.
The difference boils down to what type of value you’re trying to match:
- When you see
case 'a', that’s a character constant. In C, characters are stored as ASCII integers under the hood, so'a'is just shorthand for the integer value 97 (the ASCII code for lowercase 'a'). You’d use this when you’re matching against achartype variable, like handling user input characters. case 1is an integer constant, plain and simple. This is for matching against integer values (likeintvariables, enum values, etc.).
There’s no strict "rule" about which to use—just pick whichever matches the type of the expression in your switch statement. For example, if your switch is checking a char variable input, case 'b' makes sense; if it’s checking an int option menu_choice, case 3 is the way to go.
Great catch—this trips up a lot of folks who’re used to if/else blocks where braces are required for multiple lines. Here’s the thing:
Switch case labels are just jump targets, not the start of a new code block. Unlike if statements, the case itself doesn’t create a scope. So even if you have multiple lines of code under a case (like a *= 5; followed by break;), you don’t need braces because the code is still part of the overall switch block.
That said, braces become necessary if you want to define local variables inside a case. For example, this will cause a compiler error:
switch (x) { case 2: int temp = 42; // Error: variable declaration not allowed here without a block break; }
Wrap it in braces, and it works because you’ve created a local scope for that variable:
switch (x) { case 2: { int temp = 42; break; } }
So to sum up: Braces are optional for cases with just execution statements, but mandatory if you’re declaring variables inside the case.
内容的提问来源于stack exchange,提问作者Anon

