user1283776 user1283776 - 1 year ago 65
Objective-C Question

Make sure that random() does not return 0?

I'm looking at the documentation for random():

It returns successive pseudo-random numbers in the range from 0 to (2**31)-1.

I don't want it to return 0 ever.

I'm thinking about writing:

long rand = random() + 1;

But if I'm not mistaken, long can be 32-bits on a 32-bit processor. I guess I would risk stack overflow then.

What is the best approach to getting a random number between 1 and (2**31)-1?

Answer Source
long rand = 0;
while (rand == 0) {
    rand = random();

This will almost absolutely certainly run exactly once. In a very, very rare case (that will never happen), it will run twice.

(Note that this is just a simplified version of how arc4random_uniform works. If you can use that function, as suggested by Jeff, you should.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download