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:
要經常發表文章 最愛你了呦...............................................................
從來愛都不知它的深度,非得等到別離的時候.................................................................
臨淵羨魚,不如退而結網。.......................................................
留言支持,請繼續加油,謝謝您囉~~..................................................................
認識自己,是發現妳的真性格、掌握妳的命運、創照你前程的根源。............................................................
旁觀自己的悲傷是解脫,主觀自己的悲傷是更加悲傷................................................
Some people cannot see the wood for the trees.............................................................
弱者困於環境,智者利用環境~~加油!............................................................
Quality is better than quantity...................................................................
有夢最美啦~~加油!元氣滿點!...............................................................
跟您打聲招呼,願我們大家都更好!!..................................................................
感覺很用心經營呢!鼓勵鼓勵............................................................
要持續更新下去喲!!期待~~............................................................
Post a Comment