c -_-的基础知识

时间:2013-03-09 20:03:39

标签: gcc increment decrement

#include<stdio.h>

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

    printf("%d",j);
}

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

1 个答案:

答案 0 :(得分:0)

我生成了汇编代码(在Windows 7上使用gcc for 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。

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

相关问题