简体   繁体   中英

GCC generated assembly equivalent to continue statement in C

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?

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.

My guess is that it's a placeholder for some kind of skipped-code fixup sequence. Perhaps the nop is sometimes replaced with instructions to store registers to the stack or some such.

But to get more evidence for this, it would help to find an example where the nop is replaced with something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM