-3
#include<stdio.h>

int main()
{
    int a=2;
    int j=++a  + ++a + ++a + ++a ; 

    printf("%d",j);
}

//请告诉我这个片段的执行... //我正在使用 GCC ubuntu (12.04) 编译器。-_-

4

1 回答 1

0

我生成了汇编代码(gcc for windows on WINdows 7)[gcc -S test.c],我得到以下信息:

    .file   "increment.c"
    .def    ___main;    .scl    2;  .type   32; .endef
    .section .rdata,"dr"
LC0:
    .ascii "%d, %d\12\0"
    .text
    .globl  _main
    .def    _main;  .scl    2;  .type   32; .endef
_main:
LFB6:
    .cfi_startproc
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    andl    $-16, %esp
    subl    $32, %esp
    call    ___main
    movl    $2, 28(%esp)   ;28(%esp) = 2 (a=2)
    incl    28(%esp)       ;28(%esp) = 3 (a++)
    incl    28(%esp)       ;28(%esp) = 4 (a++)
    movl    28(%esp), %eax ;%eax = 4 (eax = a = 4)
    leal    (%eax,%eax), %edx = %eax + %eax = 8 (edx = a + a) 
    incl    28(%esp)       ;28(%esp) = 5 (a++)
    movl    28(%esp), %eax ;%eax = 5 (eax = a = 5)
    addl    %eax, %edx  ;%edx = %eax + %edx = 5 + 8 = 13 (edx = a + a + a)
    incl    28(%esp) ;28(%esp) = 6 (a++)
    movl    28(%esp), %eax ; %eax = 6 (eax = a = 6)
    addl    %edx, %eax    ;%eax = %edx + %eax = 13 + 6 = 19 (eax = a + a + a + a)
    movl    %eax, 24(%esp) 
    movl    28(%esp), %eax 
    movl    %eax, 8(%esp) 
    movl    24(%esp), %eax 
    movl    %eax, 4(%esp)
    movl    $LC0, (%esp)
    call    _printf
    leave
    .cfi_restore 5
    .cfi_def_cfa 4, 4
    ret
    .cfi_endproc
LFE6:
    .def    _printf;    .scl    2;  .type   32; .endef

计算结果后(见注释),调用 printf 函数,结果为 19。

无论如何,不​​同的编译器可以给出不同的结果。最终结果取决于编译器排列指令的方式。

于 2013-03-09T20:45:43.770 回答