Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code before the first 'case' in a switch-statement

In C it's possible to write code before the first case label. Are there any cases for which it is useful to do this or is it just a 'dead block of code' ?

E.g.:

switch (...)    {
  {
    int a = 0x2a;
    printf("%d\n", a);
  }
  case 0:
    ...
}
like image 901
tur1ng Avatar asked Jan 20 '10 12:01

tur1ng


1 Answers

I think this is less a feature than an artifact of how C treats switch/case—as just a series of jump targets without restrictions on the syntax. That's why Duff's device works and that's also why the code before the first case won't ever run.

If you look at the generated assembly you'll see that the code will just be jumped over:

    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
like image 115
Joey Avatar answered Oct 05 '22 19:10

Joey