Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC generated assembly equivalent to continue statement in C

Tags:

When a continue statement is used inside a loop in C code, GCC creates a new label with a nop instruction right before the end of the loop block and jumps to it, rather than jump to the end of the loop block itself. For instance, the following C code

for (i=0; i<10; i++) {
    puts("blah\n");
    if (i < 10) continue;
    puts("This shouldn't be printed.\n");
}

produces the following ASM equivalent (using gcc -S ):

    movl    $0, 28(%esp)
    jmp L2
L5:
    movl    $LC0, (%esp)
    call    _puts
    cmpl    $9, 28(%esp)
    jle L7
L3:
    movl    $LC1, (%esp)
    call    _puts
    jmp L4
L7:
    nop
L4:
    incl    28(%esp)
L2:
    cmpl    $9, 28(%esp)
    jle L5

(The if (i<10) part is inserted so that the compiler doesn't "optimize" the section by removing whatever follows the continue statement)

My question is, why not jump directly to L4 instead? IMO we could just as well jump to L4, am I missing something?

like image 710
susmits Avatar asked Mar 01 '10 10:03

susmits


1 Answers

What you're describing is an optimization. Surely enough, if you tell gcc to optimize (-O1 is enough), it'll do exactly what you describe.

like image 129
Michael Foukarakis Avatar answered Nov 15 '22 06:11

Michael Foukarakis