Thursday, July 15, 2010

Objective-C MIN and MAX #define wonkiness

Here’s a little odd thing I discovered when trying to use the MIN and MAX macros defined in NSObjCRuntime.h.  I had the following code (simplified):

const int MAX_OBJECTS = 10;
int numObjectsToRemove = MAX(0, myObjectArray.count - MAX_OBJECTS);


Let’s say myObjectArray.count is 1.  What would you expect numObjectsToRemove to become?

0, right?  Because (myObjectArray.count – MAX_OBJECTS) == (1 – 10) == –9, and 0 is clearly greater than –9.  But you’d be wrong.  And so was I.

You see, apparently, since the count member of NSArray is an unsigned int, the entire expression gets treated like an unsigned int.  So, since –9 in unsigned form is actually a very large number, it’s considered greater when compared to 0.  But as if that wasn’t bad enough, when it gets assigned to numObjectsToRemove, it gets treated like a normal signed int again, so its value becomes –9 again.  And you’re left wondering why –9 is considered greater than 0.

The simple fix is to force the macro to treat the whole expression like an int with a simple cast:

int numObjectsToRemove = MAX(0, (int)myObjectArray.count - MAX_OBJECTS);

13 comments:

于倫 said...

要經常發表文章 最愛你了呦...............................................................

美岑美岑 said...

從來愛都不知它的深度,非得等到別離的時候.................................................................

洪瑋婷洪瑋婷 said...

臨淵羨魚,不如退而結網。.......................................................

RicoLisi0802志竹 said...

留言支持,請繼續加油,謝謝您囉~~..................................................................

昱吳宏昱吳宏 said...

認識自己,是發現妳的真性格、掌握妳的命運、創照你前程的根源。............................................................

馬志榮惠玲成 said...

旁觀自己的悲傷是解脫,主觀自己的悲傷是更加悲傷................................................

怡于名君 said...

Some people cannot see the wood for the trees.............................................................

周志v豪 said...

弱者困於環境,智者利用環境~~加油!............................................................

偉曹琬 said...

Quality is better than quantity...................................................................

家則治則治則治瑋 said...

有夢最美啦~~加油!元氣滿點!...............................................................

洪涛 said...

跟您打聲招呼,願我們大家都更好!!..................................................................

孫邦柔 said...

感覺很用心經營呢!鼓勵鼓勵............................................................

瑰潼 said...

要持續更新下去喲!!期待~~............................................................