Coding

rand() and srand() in C: How to Generate Random Numbers

rand() returns a pseudorandom int between 0 and RAND_MAX, and srand(seed) chooses where that sequence starts. Call srand(time(NULL)) once at the start of main(), then call rand() as often as you need.

Both functions are declared in <stdlib.h>. time() comes from <time.h>.

The minimal rand() example

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    srand((unsigned int)time(NULL));   /* seed once */

    for (int i = 0; i < 5; i++) {
        printf("%d\n", rand());
    }
    return 0;
}

Each run prints five integers between 0 and RAND_MAX. The values change from run to run because the seed changes with the clock. Remove the srand line and every run prints the same five numbers.

What rand() returns and what RAND_MAX is

The signature is int rand(void);. It takes no arguments and has no error return. The result is always in the closed range 0 to RAND_MAX, both ends included.

RAND_MAX is implementation defined. The C standard only guarantees it is at least 32767, and Microsoft's C runtime documents it as exactly 32767. On such a platform rand() has only 32,768 possible outputs. Other C libraries use a larger value, so print it with printf("%d\n", RAND_MAX); if your code depends on it, and never hard-code 32767.

What srand() does and why the same numbers repeat

void srand(unsigned int seed); sets the starting state of the generator. The guarantee is that seeding with the same value again reproduces the same sequence. If rand() is called before any srand(), it behaves as if you had called srand(1). That is why a program that never seeds prints identical numbers every time.

The repeatability is useful. Seed with a fixed number in a test, and a failing case can be replayed exactly. Microsoft's own example does this with srand(1792).

Example output, from Microsoft's documentation of that program (the numbers differ on other C libraries, because the algorithm is not specified by the standard):

5890
1279
19497
1207
11420

Seed once, not before every call

time(NULL) returns the current time in whole seconds on most systems. Two calls within the same second return the same seed. This is a common mistake:

int roll_die(void)
{
    srand((unsigned int)time(NULL));   /* wrong: reseeds on every call */
    return 1 + rand() % 6;
}

Calling roll_die() in a tight loop restarts the sequence from the same seed each time, so it returns the same face repeatedly until the clock ticks over. Move srand into main() and run it once.

How to get a random number in a range

The usual advice is rand() % n, which gives 0 to n-1. It is easy to write, but it is slightly biased. The arithmetic is simple. With RAND_MAX equal to 32767 there are 32,768 possible outputs. Divide them into six remainders:

32768 = 6 * 5461 + 2

Remainders 0 and 1 occur 5,462 times each, and remainders 2 to 5 occur 5,461 times each. So 1 + rand() % 6 favours 1 and 2 very slightly. For a game this is harmless. For anything where fairness matters, avoid it. cppreference's example notes the same problem and uses division instead, rerolling values that fall outside the range:

/* Returns a value in [low, high], inclusive. Requires low <= high
   and a range no larger than RAND_MAX + 1. */
int rand_range(int low, int high)
{
    unsigned int width = (unsigned int)(high - low) + 1u;
    unsigned int bucket = (RAND_MAX + 1u) / width;
    unsigned int pick;

    do {
        pick = (unsigned int)rand() / bucket;
    } while (pick >= width);

    return low + (int)pick;
}

Here bucket is how many raw values map to each result. A raw value that lands in the leftover tail at the top gives pick >= width, is thrown away, and rand() is called again. Every result in the range is then equally likely. The loop almost always finishes in one or two iterations.

A die roll is rand_range(1, 6). A random index into an array of length n is rand_range(0, n - 1); see arrays in C for how indexing and array sizes work.

Random floating-point numbers

To get a double from 0.0 to 1.0, divide by RAND_MAX:

double unit = (double)rand() / RAND_MAX;

This can return exactly 1.0, because rand() can return RAND_MAX. If you need the half-open range [0, 1), divide by RAND_MAX + 1.0 instead. Remember that with a 32,768-value generator the result has only 32,768 distinct steps, so it is a coarse approximation of a continuous random number.

Print a list of unique random numbers

A common exercise is to draw, say, 6 distinct numbers from 1 to 49. Calling rand_range six times can repeat a value. One simple fix is to keep an array of what has been drawn and redraw on a collision:

int drawn[6];
int count = 0;

while (count < 6) {
    int candidate = rand_range(1, 49);
    int seen = 0;

    for (int i = 0; i < count; i++) {
        if (drawn[i] == candidate) {
            seen = 1;
            break;
        }
    }
    if (!seen) {
        drawn[count++] = candidate;
    }
}

The inner loop is an ordinary for loop. This approach is fine when you draw a few values from a large pool. If you need most of the pool, shuffle an array of all candidates instead, so the work does not grow as the pool empties.

Limits of rand()

  • No quality guarantee. The standard does not specify the algorithm. cppreference notes that some past implementations had serious flaws in randomness, distribution and period, and gives an example where the lowest bit alternated 1, 0, 1, 0 on successive calls. The Linux man page says the low-order bits are about as random as the high-order bits in the Linux C library, but much less random on older implementations and on many other systems. This is another reason to scale with division rather than %.
  • Not for security. Microsoft's documentation says numbers from rand aren't cryptographically secure and points to rand_s or the C++ <random> header. cppreference gives the same warning. Do not use rand() for passwords, session tokens or keys. If you only need a random password, a password generator saves you from writing code at all.
  • Not guaranteed thread-safe. cppreference states that rand() is not guaranteed to be thread-safe. POSIX's rand_r() keeps its state in a caller-supplied variable, but it is weak because the state is so small, and it is deprecated in glibc and obsolete in POSIX.1-2008. The man page suggests drand48_r(3) instead, and cppreference suggests the drand48 family.
  • Small output range on some platforms. With a RAND_MAX of 32767 you cannot cover a range larger than 32,768 values evenly. Microsoft's example comments say this directly. Combining two calls is a workaround, but at that point a better generator is a cleaner answer.

Which function to use instead

For simulations, games and tests where you only need numbers that look random, rand() with a once-only srand() is adequate. When you need better statistical quality or long sequences, use a generator your platform documents properly, such as random() on POSIX systems (the Linux man page recommends it when portable, good randomness matters) or the drand48 family. For anything secret, use rand_s on Windows, which Microsoft documents as the more secure alternative, or your operating system's secure random source.

If your numbers still look wrong

If every run prints the same values, check that srand is called, and that it is called before the first rand(). If a loop prints one value many times, you are reseeding inside the loop. If results cluster at the low end of a range, check whether you cast to an integer before dividing: rand() / RAND_MAX is integer division and yields 0 almost always, so cast to double first, as in the example above. And if a compiler warns about converting time_t to unsigned int, the explicit cast in srand((unsigned int)time(NULL)) is intentional: only the low bits matter for a seed.

Frequently asked questions

Why does rand() give the same numbers every time I run my program?
If you never call srand(), rand() behaves as if it had been seeded with srand(1), so it produces the same sequence on every run. Call srand() once at the start of main() with a value that changes between runs, such as time(NULL), to get a different sequence each time.
Should I call srand(time(NULL)) before every rand() call?
No. Call it once. time(NULL) changes only once per second, so seeding repeatedly inside a loop or function restarts the generator from the same seed and returns the same value many times in a row.
What is RAND_MAX?
RAND_MAX is a macro in <stdlib.h> holding the largest value rand() can return. The C standard guarantees it is at least 32767; the exact value depends on the implementation. Microsoft's C runtime documents it as 32767.
Is rand() safe for passwords, tokens or encryption keys?
No. rand() produces a well-known, reproducible sequence from a small seed, and the documentation from cppreference and Microsoft both say it is not suitable for cryptography. Use an operating-system source of secure randomness instead, such as rand_s on Windows, which Microsoft documents as the more secure alternative.

Sources