C语言题目:(见下面)

来源:百度知道 编辑:UC知道 时间:2024/06/28 01:51:28
求结果
int a=2,b=5,c;
c=a>b?a++:b++,a+b;
printf("%d",c):答案是5....我算的结果不是....
大家看我的思路哪里出错了.我认为2>5是假,做冒号后面的b++.b为5,b++不变也为5.a+b=5+2=7...

重点:在C语言中赋值运算符优先级比逗号运算符要高;
所以先做c=a>b?a++:b++ 就是把c的值算出来,然后再做c,a+b;
这个逗号运算表达式。因为a>b为假,做c=b++,所以c=5 b=6
你要求打印C的值,所以打印出来C的值就是5。

c=a>b?a++:b++,a+b;
这句话中b先用再++,
换句话讲就是先a+b,再c=b;最后b才自加,
那么a+b是7(没用的),c=b就是c=5,b++便是6;
输出c,当然是5!

.file "test.c"
.section .rodata
.LC0:
.string "%d"
.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 $36, %esp
movl $2, -16(%ebp) # a = 2
movl $5, -12(%ebp) # b = 5
movl -16(%ebp), %eax # %eax = a
cmpl -12(%ebp), %eax
jle .L2 # 程序跳转到了 .L2
movl -16(%ebp), %eax
movl %eax, -24(%ebp)
addl $1, -16(%ebp)
jmp .L4
.L2: # 执行:后面的
movl -12(%ebp), %eax # %eax = 5
movl %eax, -24(%ebp) # -24(%ebp) = 5,这里注意一下,-24(%ebp) 以后会赋给c的
addl $1, -12(%ebp) # b += 1, 这里b自增1无用