I've stumbled into a quite surprising problem while doing some iOS stuff with random numbers.
Compare these:
a)
int xOffsetSign = randomIntWithUpperLimit(2) ? 1:-1;
int yOffsetSign = randomIntWithUpperLimit(2) ? 1:-1;
int xOffset = randomIntWithUpperLimit(50) * xOffsetSign;
int yOffset = randomIntWithUpperLimit(50) * yOffsetSign;
b)
int xOffset = randomIntWithUpperLimit(50) * randomIntWithUpperLimit(2) ? 1:-1;
int yOffset = randomIntWithUpperLimit(50) * randomIntWithUpperLimit(2) ? 1:-1;
This is the random function:
static inline int randomIntWithUpperLimit(unsigned int upperLimit) {
return arc4random_uniform(upperLimit);
}
In my mind, both a) and b) should produce random numbers in the [-49,49] range. However, only a) works. b) only produces numbers in the [-1, 1] range.
It seems that the second random part of each call gets resolved first, is cached, and then reused for the first part of the line, regardless of upper bound.
Can somebody explain and clarify why b) won't work?