發信人tinlans.bbs@whshs.cs.nccu.edu.tw (汀),
看板Programming
標 題Re: [問題] 如果哪天我也遇到這個爛題目,該怎麼答?
發信站政大狂狷年少 (Sun Feb 25 12:17:21 2007)
轉信站ptt!ctu-reader!ctu-peer!news.nctu!netnews.csie.nctu!news.cs.nthu!WHSHS
其實用 GCC 要同時觀察到 26 跟 27 的方法非常的簡單,
先來寫兩個檔案:
// test1.cxx
#include <iostream>
using namespace std;
extern int i;
int main()
{
i = i++ + ++i;
cout << i << endl;
return 0;
}
// test2.cxx
int i = 12;
這樣會得到 27:
g++ test1.cxx test2.cxx -o test
用 -O -O2 -O3 會得到 26,
上述是 GCC 3.4.4 得到的結果。
我想應該有人已經猜到,
這樣拆兩個檔案是為了避免 optimization 直接算出 constant 結果。
其實 result 還不是只有這兩種,
GCC 4.x 起改用 recursive descent 的方式撰寫 LL(1) 的 C parser,
結果沒下 -O 出來是 13,
而 -O -O2 -O3 出來都是 14,
拿 GCC 4.2 和 4.3 跑出來都是這樣。
想要生出另一種值的話,
可以這樣寫:
// test3.cxx
#include <iostream>
using namespace std;
int main()
{
volatile int i = 12;
i = i++ + ++i;
cout << i << endl;
return 0;
}
GCC 3.4.4 會生出 25,
GCC 4.2 和 4.3 會生出 13 來。
如果好奇為什麼,
用 -S 觀察組語看看吧,
順便對照標準規格書上的那段話,
應該就會有心得了。
--
Name: Tseng, Ling-hua E-mail Address: uranus@it.muds.net
School: National Tsing Hua University Department: Computer Science
Interesting: C++, Compiler, PL/PD, OS, VM, Large-scale software design
Researching: Software pipelining for VLIW architectures
Homepage:
https://it.muds.net/~uranus
--
╔═══╗ ┼────────────────────────╮
║狂狷 ║ │
* Origin:[ 狂 狷 年 少 ] whshs.cs.nccu.edu.tw ╰─╮
║ 年少║ ┼╮
< IP:140.119.164.252 > ╰─╮
╚╦═╦╝ ╰
* From:61-230-219-136.dynamic.hinet.net
─╨─╨─ KGBBS ─ ◎ 遨翔"BBS"的狂狷不馴;屬於年少的輕狂色彩 ◎
[修改]tinlans:61-230-219-136.dynamic.hinet.net 18/06/01 11:58:59
推 meltice:強者 218.211.17.52 02/25 13:23
推 FedoraCore:XD 我還真的不知道 59.113.173.107 02/25 20:02
推 YuYuHo:大師~趕快拿香來拜~Qrz 61.223.233.16 02/25 20:30
推 bigbite:真的是強者..140.113.138.113 02/26 00:29
推 buganini:太強惹..!@$#%^!!!!!!!!!!! 163.22.93.130 02/26 20:14