05 Mar 12
20:12

Return of the unsigned int gotcha for the unary ‘-‘ operator

I came across another unsigned int issue today.
If you have an unsigned int and you negate it with the unary ‘-‘ operator, you will just get a really large unsigned integer value, and not a negative value.
From my last post about unsigned int, you can’t do

smallInt - unsignedInt

and expect a negative value because this converts the int to unsigned int.

That was for operators that worked on two values. Seems like the lower precedence of unsigned in still prevails with the unary ‘-‘ operator.
According to this stack overflow post the value you get is

UINT_MAX - origUIntValue + 1

That seems to make sense even though I haven’t thought it out. The lesson here is to cast your goddamn unsigned ints when dealing with things that require negative intness.
Here’s my lldb (xcode’s gdb replacement for llvm) output that inspired this post:

(lldb) print -m_labelTex.pixelsWide
(NSUInteger) $3 = 4294967232
(lldb) print m_labelTex.pixelsWide
(NSUInteger) $4 = 64
(lldb) print -((int)m_labelTex.pixelsWide)
(int) $6 = -64
(lldb) print 0 - m_labelTex.pixelsWide
(unsigned int) $7 = 4294967232
(lldb) print ((int) 4) - m_labelTex.pixelsWide
(unsigned int) $8 = 4294967236