請教c語言高手

2009-06-30 11:36 am
main(){int x=9,y=6; x=(y+=x?=y)?x; printf("%d\n",y);}
請問為何y=9
謝謝
更新1:

打錯了,對不起 main(){int x=9,y=6; x=(y+=x-=y)-x; printf("%d\n",y);} 請問為何y=9 謝謝

更新2:

you can.

回答 (4)

2009-07-01 2:59 pm
✔ 最佳答案
Can I answer this in English?

2009-07-01 06:59:15 補充:
This is an old trick used to swap two integers fast. Note that the operator ==, +=, -=, ^= ... are all evaluated from right to left because their associativity is from right to left. I have rewrote your program into the following for ease of explaination:

line # code
1 x
2 =
3 ( y
4 +=
5 x
6 -=
7 y)
8 -
9 x

Now, due to the fact that = on line 2 has right associativity, (y+=x-=y)-x has to be evaluated first. Again, += has the same issue. Thus, x-=y has to be evaluted first. Also, -= will have the same order of evaluation. Therefore, y has to be evaluated first.

Now, y at line# 7, at this moment has a value of 6. Therefore, x-=6 will give a value of 3 and assigned to x at line #5.

Afterwards, y+=3 will be evaluated and y at line# 3, will be assigned a value of 9.
At the end, x at line #1, will be assigned a value of 9-3 which is 6.

I used to use is:
y^=x^=y^=x;

This is not used anymore in real code due to the advance in compiler technology (I was told).


2009-07-01 4:33 pm
int x=9,y=6; x=(y+=x-=y)-x;
x-=y => x=x-y => x=9-6 => x=3
y+=x => y=y+x => y=6+3 => y=9
x=9-3 => x=6

printf("x=%d,y=%d\n",x,y);

=>

x=6,y=9
2009-07-01 8:01 am
好利害的程式碼.可能是我的編譯器太爛,無法編譯出並執行這個程式,並輸出y結果等於9
2009-06-30 5:10 pm
這程式碼本身有問題吧
沒法編譯的
x=(y+=x?=y)?x;
我猜你是想用到一種運算式例如

z = y > x ? y : x; //這會取x,y的最大值給z

格式:
(條件判斷) ? (條件成立時回傳值) : (不成立時回傳值)


收錄日期: 2021-05-01 23:51:46
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090630000015KK01267

檢視 Wayback Machine 備份