objective-carc4random

Strange result from arc4random_uniform(). Whats happened


yesterday i had the follow code:

NSInteger test = arc4random_uniform(10)-5;

if i checked via debugger whats inside test, sometimes it was not a number between -5 and 5. Sometime it was a random big integer.

After i changed the code to this:

NSInteger test = arc4random_uniform(10);
test -= 5;

i was only get a number between -5 and 5. I'm pretty new to Objectiv C and normaly i only write C / C++. But this makes no sense for me.

Can someone explain what happend?


Solution

  • The arc4Random family of functions return u_int32_t. The "u_" means unsigned, and determines the type of the expression with the literal 5. So that first expression will (about half the time, for randoms < 5) produce an unsigned negative, which will be treated as nearly UINT_MAX.

    The second expression casts the random as a signed int first, so the subsequent subtraction works as expected.