C++ srand()

The srand() function in C++ seeds the pseudo random number generator used by the rand() function.

The srand() function in C++ seeds the pseudo random number generator used by 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).


srand() prototype

void srand(unsigned int seed);

The srand() function takes an unsigned integer as its parameter which is used as seed by the rand() function.

It is defined in <cstdlib> header file.


srand() Parameters

  • seed: A seed value of type unsigned int

srand() Return value

  • None

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


Example 1: How srand() function works?

#include<iostream>
#include<cstdlib>
using namespace std;

int main()
{
	int random = rand();
	/* No srand() calls before rand(), so seed = 1*/
	cout << "Seed = 1, Random number = " << random << endl;

	srand(5);
	/* Seed = 5 */
	random = rand();
	cout << "Seed = 5, Random number = " << random << endl;

	return 0;
}

When you run the program, the output will be:

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

It is a good practice to seed the pseudo random number generator only once at the beginning of the program and before any calls of rand(). It should not be seeded every time we need to generate a new set of numbers.

The standard practice is 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). The value of seed changes with time. So every time we run the program, a new set of random number is generated.


Example 2: srand() function with time()

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main()
{
	srand(time(0));
	int random = rand();

	cout << "Seed = " << time(0) << endl;
	cout << "Random number = " << random << endl;
return 0;
}

When you run the program, the output will be:

Seed = 1485583981
Random number = 22589