Search code examples
objective-cgnusteparc4random

Why is arc4random returning negative numbers sometimes?


I'm using arc4random() to generate numbers in a certain range. However, I will intermittently receive negative numbers. I'm not doing anything strange:

if([aBug x] == -1) {
    x = arc4random() % columns;
}

if([aBug y] == -1) {
    y = arc4random() % rows;
}

Here, x and y sometimes get set to negative values. x and y are both of type int.


Solution

  • Sounds like you want to declare x and y to be of type u_int32_t instead of int. I.e., you should be using unsigned variables instead of signed.

    Or, use a signed integer that's larger than 32 bits (e.g., uint64_t/long long).