Nested if statements and “&&” operator

断了今生、忘了曾经 提交于 2019-12-01 04:01:46

They're exactly identical.

To test this yourself, run gcc -S test.c (presuming that this is where you've put your source) and observe the contents of test.s.


Here's how the nested-if approach compiles in gcc 4.8.1 with default options (annotated with comments):

main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    $0, %eax
    call    A                        # try to call A
    testl   %eax, %eax               # look at its return value
    je  .L3                          # short-circuit if it returned 0
    movl    $0, %eax                 # ...repeat for B, et al.
    call    B
    testl   %eax, %eax
    je  .L3
    movl    $0, %eax
    call    C
    testl   %eax, %eax
    je  .L3
    movl    $0, %eax
    call    D
    testl   %eax, %eax
    je  .L3
    movl    $0, %eax
    call    doSomething
.L3:
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc

Here's how the && approach compiles:

main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    $0, %eax
    call    A                           # try to call A
    testl   %eax, %eax                  # look at its return value
    je  .L3                             # short-circuit if it returned 0
    movl    $0, %eax                    # ...repeat for B, et al.
    call    B
    testl   %eax, %eax
    je  .L3
    movl    $0, %eax
    call    C
    testl   %eax, %eax
    je  .L3
    movl    $0, %eax
    call    D
    testl   %eax, %eax
    je  .L3
    movl    $0, %eax
    call    doSomething
.L3:
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!