C++ srand()

The srand() function in C++ seeds the pseudo-random number generator used by the rand() function. It is defined in the cstdlib header file.

Example


srand() Syntax

The syntax of srand() is:

srand(unsigned int seed);

srand() Parameters

The srand() function takes the following parameter:

  • seed - a seed value of type unsigned int

srand() Return value

The srand() function doesn't return any value.


srand() Prototype

The prototype of srand() as defined in the cstdlib header file is:

void srand(unsigned int seed);

Here, the srand() parameter seed is used as seed by the rand() function.


Working of C++ srand()

The srand() function sets the seed for the rand() function. The seed for rand() function is 1 by default.

It means that if no srand() is called before rand(), the rand() function behaves as if it was seeded with srand(1).

However, if an srand() function is called before rand, then the rand() function generates a number with the seed set by srand().

Note: A "seed" is the starting point for a sequence of pseudo-random numbers. To learn more, visit this link in StackOverflow.


Example 1: C++ srand()

Output

Seed = 1, Random number = 41
Seed = 5, Random number = 54

srand() Standard Practices

  1. The pseudo-random number generator should not be seeded every time we generate a new set of numbers i.e. it should be seeded only once at the beginning of the program, before any calls of rand().
  2. It is preferred to use the result of a call to time(0) as the seed. The time() function returns the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e. the current unix timestamp).

    As a result, the value of seed changes with time. So every time we run the program, a new set of random numbers is generated.

Example 2: srand() with time()

Output

Seed = 1629892833
Random number = 5202