gpt4 book ai didi

switch 语句中第一个 'case' 之前的代码

转载 作者:太空狗 更新时间:2023-10-29 16:33:04 25 4
gpt4 key购买 nike

在 C 中,可以在第一个 case 标签之前编写代码。是否存在这样做有用的情况,或者它只是一个“死代码块”?

例如:

switch (...)    {
{
int a = 0x2a;
printf("%d\n", a);
}
case 0:
...
}

最佳答案

我认为这与其说是一个特性,倒不如说是 C 处理 switch/case 的一个产物——只是一系列没有语法限制的跳转目标。这就是为什么 Duff's device有效,这也是第一个 case 之前的代码永远不会运行的原因。

如果您查看生成的程序集,您会发现代码将被跳过:

    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

关于switch 语句中第一个 'case' 之前的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2101393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com