objective c - Using MAX and math on array count -


i have misbehaving code looks this: (events nsarray 1 element when code executes)

max(0, self.events.count-2) 

i expect result of expression 0, produces -1. checking nsobjcruntime.h, max() looks this:

#define max(a,b)    ({ __typeof__(a) __a = (a); __typeof__(b) __b = (b); __a < __b ? __b : __a; }) 

with lldb, see following:

(lldb) p (int)[[self events] count] (int) $0 = 1 (lldb) p (int)[[self events] count] - 2 (int) $1 = -1 (lldb) p (bool)[[self events] count] - 2 < 0 (bool) $2 = true (lldb) p (bool)0 > [[self events] count] - 2 (bool) $3 = false 

huh? maybe it's operator precedence, but...

(lldb) p (bool)(0 > [[self events] count] - 2) (bool) $4 = no (lldb) p (bool)(0 > ([[self events] count] - 2)) (bool) $5 = no 

weird debugger changes on caps bool/yes/no after first funny answer. 1 might suppose foregoing code behave differently:

max(0, self.events.count-2) 

...but, , maybe i'm happy sanity here, works wrongly same way. must missing basic syntax, cannot spot it.

the problem due fact count property unsigned. result of unsigned 1 - 2 not -1, it's huge number. huge number returned since greater 0.

but cast unsigned result signed , gets interpreted -1 leaving think result incorrect.

try:

p [[self events] count] - 2 

and see large value.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -