如果有表达式 a = i++ 它等价于 a = i ; i = i + 1;
如果有表达式 a = ++i 它等价于 i = i + 1; a = i;
# vi test.c
---------------------------------
#include <stdio.h>
#include <string.h>
int main()
{
int
x = 1
;
int
y = x--
;
}
# gcc -S test.c
# vi test.s
---------------------------------
.file "test.c"
.text
.globl main
.type main, @function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $16, %esp
movl $1, -12(%ebp)
movl -12(%ebp), %eax
movl %eax, -8(%ebp)
subl $1, -12(%ebp)
addl $16, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
.size main, .-main
.ident "GCC: (GNU) 4.1.2 (Ubuntu 4.1.2-0ubuntu4)"
.section .note.GNU-stack,"",@progbits
# vi test.c
---------------------------------
#include <stdio.h>
#include <string.h>
int main()
{
int x = 10;
int
y = --x
;
}
# gcc -S test.c
# vi test.s
---------------------------------
.file "test.c"
.text
.globl main
.type main, @function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $16, %esp
movl $10, -12(%ebp)
subl $1, -12(%ebp)
movl -12(%ebp), %eax
movl %eax, -8(%ebp)
addl $16, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
.size main, .-main
.ident "GCC: (GNU) 4.1.2 (Ubuntu 4.1.2-0ubuntu4)"
.section .note.GNU-stack,"",@progbits
Linux + GCC
------------------------------------------------
#include <stdio.h>
int main()
{
int i = 5, j = 5, p, q;
p = (i++) + (i++) + (i++);
q = (++j) + (++j) + (++j);
printf("i = %d\n", i); // 8
printf("j = %d\n", j); // 8
printf("p = %d\n", p); // 15
printf("q = %d\n", q); // 22
}
(1)
由于i++语句是语句级别的,也就是只有在本语句执行完后才做加1操作。
所以,p = (i++) + (i++) + (i++);这里最后的p的值应该为5 + 5 + 5 = 15,而在程序运行接收后,i的值开始做加1操作,因此i的值应该为5 + 1 + 1 + 1 = 8。所以在第一个语句中,最后:p = 15, i = 8。
(2) 在对于++i的这种操作就不像i++操作那么简单了。这时需要分操作系统去考虑问题了。
在Windows操作系统下使用TC和VC执行此程序后结果是q = 24, j = 8,这个很好理解,因为++i操作是先做加1操作然后再进行本语句操作,所以,j在经过过三次加1操作后变成了8,而q的值在j做完加1操作后执行的结果,故q的值为8 + 8 + 8 = 24。
在Linux操作系统下使用gcc编译器执行此程序后的结果是:q = 22, j = 8,这个结果看到后确实让我大吃一惊。
分析其汇编代码得知: 先做前两个++j加1操作,此时j = 7,将前两个j相加后(7 + 7),再对第三个++j进行自增运算(j = 8),最后加上第三个j(7 + 7 + 8 = 22)
其实质相当于:
q = (
((++j) + (++j))
+ (++j));