内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
在C中,可以在第一个case
标签之前编写代码。有没有有用的做法,或者它只是一个'死代码块'?
例如:
switch (...) {
{
int a = 0x2a;
printf("%d\n", a);
}
case 0:
...
}
声明范围仅限于switch
块的变量会很有用(但请注意,这些变量的任何初始值将被跳过):
switch (...)
{
int n;
case 0:
...
}
从理论上讲,你也可以把代码放在那里,你可以使用goto
。
如果你看看生成的程序集,你会发现代码只会被跳过:
mov ecx, DWORD PTR _x$[ebp]
mov DWORD PTR tv64[ebp], ecx
cmp DWORD PTR tv64[ebp], 0 ; here begins the switch
je SHORT $LN1@main ; jump to case 0
jmp SHORT $LN4@main ; jump out of the switch
; Line 8
mov DWORD PTR _a$752[ebp], 42
; Line 9
mov edx, DWORD PTR _a$752[ebp] ; here we have the dead code
push edx
push OFFSET $SG754
call _printf
add esp, 8
$LN1@main: ; and here case 0
; Line 12
push OFFSET $SG756
call _printf
add esp, 4
$LN4@main:
; Line 15
xor eax, eax
mov esp, ebp
pop ebp
ret 0