function
<cstdlib>

srand

void srand (unsigned int seed);
Initialize random number generator
The pseudo-random number generator is initialized using the argument passed as seed.

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.

In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). This is distinctive enough for most trivial randomization needs.

Parameters

seed
An integer value to be used as seed by the pseudo-random number generator algorithm.

Return Value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* srand example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}


Possible output:

First number: 41
Random number: 13
Again the first number: 41

Data races

The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand.

Some libraries provide an alternative function of rand that explicitly avoids this kind of data race: rand_r (non-portable).

C++ library implementations are allowed to guarantee no data races for calling this function.

Exceptions (C++)

No-throw guarantee: this function never throws exceptions.

See also