Re: [閒聊] i++ is undefined behavior?
※ 引述《ah7675 (阿懋)》之銘言:
: 最近因為同事在code review時表示 i++會隨編譯器實作而有不同行為
: 所以要求我不要用這種寫法,到這邊應該很多人會說:"沒錯啊,這你都不懂?"
: 關鍵在於他舉的例子是這樣的
: i=10;
: val = array[i++];
: val equals array[10] or array[11]?
: 我整個傻住了,我的理解是,答案絕對是val=array[10]
: 而隨編譯器會變化的地方是,在該expression/statement所構成的
: 數個指令中"遞增"的時機可能不同,所以如果在一個expression中存取i
: 兩次以上會造成未定義行為
: 但suffix increament operator必定是先return再遞增
: 請問我的理解才是錯的嗎?
: 那GLIBC裡的strcmp實作也是不可靠的嗎?
: https://fossies.org/dox/glibc-2.21/string_2strcmp_8c_source.html
: 還有另一個例子是說const global variable is better than Macro??
: 理由是global variable只有一份、用再多次也只是reference同一份
: 但是macro假設被使用10次就會造成code size增加10倍
: 用來舉例的型別是int
: 這也是顛覆了我一直以來的觀念,讓我相當震撼
: 我應該趕快請前輩喝飲料順便多請教他,還是趁試用期還沒過趕快離職?
: 請各位給我一些意見,感謝!
第二個問題:
Effective C++ Item2: Prefer consts, enums, and inlines to #defines
簡單的列一下書上所提的#define的4個缺點,順便複習一下
舉例 #define ASPECT_RATIO 1.653
1. The symbolic name ASPECT_RATIO may never be seen by compilers;
it may be removed by the preprocessor before the source code ever
gets to a compiler.
2. The preprocessor's blind substitution of the marco name could
result in multiple copies in your object code.
3. Marco breaks class encapsulation.
4. When using marcos, you have to remember to parenthesize all the
arguments in the marco body.
第一個問題:
post increment 實做的結果就是先把原值存一個copy,increment i,再回傳copy
其中increment i這個動作是用++i來做的
所以可以說 i++ is implemented in terms of ++i
只要這個核心概念是不變的,i++就是會回傳遞增前的值,而++i則是回傳遞增後
的值
補充:
關於你提到的undefined behavior,要視是回傳值的形態而定
如果回傳形態是const by value,或reference to const,而你又想再去改變它的值
就會產生問題
例如i++的回傳形態是const by value,因此寫i++++就會產生compiler error
這其實是用來提醒使用者避免這樣的用法
(可參考More Effective C++ Item6)
希望有回答到你的問題^^
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.1.232.252
※ 文章網址: https://www.ptt.cc/bbs/Soft_Job/M.1429896994.A.283.html
※ 編輯: developers (106.1.232.252), 04/25/2015 02:28:10
推
04/25 12:33, , 1F
04/25 12:33, 1F
→
04/25 13:33, , 2F
04/25 13:33, 2F
→
04/25 13:34, , 3F
04/25 13:34, 3F
→
04/25 13:35, , 4F
04/25 13:35, 4F
→
04/25 17:38, , 5F
04/25 17:38, 5F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 6 篇):