0

I'm trying to put some objects in the screen at random positions.

I use arc4random() to generate a new random number.

But it seems that the function is not working properly, here's the code and traced result:

Code :

UIView *stateView = [[UIView alloc] initWithFrame:CGRectMake( (arc4random()%700)-100 , (20 * 91) + 378 + ((arc4random()%600)+200), 325 , 188)];

NSLog(@"Note %d : X = %f , Y = %f",i,stateView.frame.origin.x,stateView.frame.origin.y);


**********************


NSLog Output :

Note 5 : X = 4294967040.000000 , Y = 2552.000000

Is this a bug or I'm doing wrong with the generator ?

Sepehrom
  • 1,335
  • 2
  • 16
  • 33

1 Answers1

0

According to the documentation for arc4random(), the return type is u_int32_t, which is an unsigned type. In the expression

(arc4random()%700)-100

the calculation, including the subtraction, is done using unsigned arithmetic. You are getting unsigned arithmetic overflow. To fix this, cast to a signed integer type before doing the subtraction:

((int) (arc4random() % 700)) - 100

The result of this will be an integer from -100 through 599.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285