Basic Random Number Generation

suggest change

The function rand() can be used to generate a pseudo-random integer value between 0 and RAND_MAX (0 and RAND_MAX included).

srand(unsigned int) seeds the pseudo-random number generator. Each time rand() is seeded with the same seed, it must produce the same sequence of values. Seed it once before calling rand(); repeatedly reseeding can reduce the quality of the generated sequence.

A common way to vary the sequence between runs is to seed with time(NULL). time returns time_t and can fail by returning (time_t)-1; the value is also converted to unsigned int for srand. If you need a deterministic sequence, seed with the same value on each program start. That is useful in debug runs so bugs are reproducible.

Seed the generator explicitly. If you do not, it behaves as if you called srand(1).

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

int main(void) {
    int i;
    srand(time(NULL));
    i = rand();

    printf("Random value between [0, %d]: %d\n", RAND_MAX, i);
    return 0;
}

Possible output:

Random value between [0, 2147483647]: 823321433

Notes:

The C Standard does not guarantee the quality of the random sequence produced. In the past, some implementations of rand() had serious issues in distribution and randomness of the generated numbers. The usage of rand() is not recommended for serious random number generation needs, like cryptography.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents