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

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

int main() {

// set seed to 10 srand(10);
// generate random number int random = rand(); cout << random; return 0; } // Output: 71

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()

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

int main() {
  int random = rand();
  
  // srand() has not been called), so seed = 1
  cout << "Seed = 1, Random number = " << random << endl;

// set seed to 5 srand(5);
// generate random number random = rand(); cout << "Seed = 5, Random number = " << random << endl; return 0; }

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()

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

int main() {

// set seed to time(0) srand(time(0));
// generate random number int random = rand(); // print seed and random number cout << "Seed = " << time(0) << endl; cout << "Random number = " << random; return 0; }

Output

Seed = 1629892833
Random number = 5202
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges