作者adrianshum (Alien)
看板Programming
標題Re: [請益] for迴圈 i++ or ++i ?
時間Mon Dec 10 22:33:29 2007
※ 引述《solonchuang (企鵝寶寶)》之銘言:
: ※ 引述《adrianshum (Alien)》之銘言:
: : 原因大概因為 i++ 看起來比較順眼,
: : 還有其實寫了很久程式的人也不太會留意
: : 這個分別而已
: : Alien
: 畢竟用了非常久的i++,
: 追根究底請教一下, 為什麼 ++i 比較好?
由於 postfix ++ (或 --) return 的值是
increment/decrement 前的值。假設現在用的
是一個 class 而非一般的 integer:
class MyClass {
public:
MyClass& operator++(); // prefix increment
MyClass operator++(int); // postfix increment
private:
int value;
}
MyClass& MyClass::operator++() {
++this.value;
return *this;
}
MyClass MyClass::operator++(int) {
MyClass tempData;
tempData.value = this.value;
++this.value;
return tempData;
}
由於性質上的差異,postfix ++/-- 無可避免要
一個 temp variable 來作為 return value.
本身的額外memory usage, copy construction etc
都是帶來額外負擔的部份。
Alien
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 203.218.221.132
→ james732:請問C語言也會存在這樣的差異嗎? 59.104.63.223 12/10 22:36
推 sunneo:會220.132.228.138 12/10 22:39
推 solonchuang:謝謝你. 123.195.42.87 12/10 22:47
→ adrianshum:像前面有人提過,一般compiler會最佳化203.218.221.132 12/10 22:49
→ adrianshum:基於 C 沒有 operator overloading,203.218.221.132 12/10 22:50
→ adrianshum:pre/postfix incr 的分別就不太大了.203.218.221.132 12/10 22:50
推 FlyinDeath:樓上專業~ 61.231.196.82 12/11 11:42
推 GreatShot:++this->value; 220.133.110.47 12/14 02:17