Trusted answers to developer questions

What are the rand and srand functions in C++?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.

svg viewer

Both of the functions are defined in the header:

#include <cstdlib>

Code

In the code below, the rand() function is used without seeding. Therefore, every time you press the run button, ​it generates the same number.

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int i = rand();
cout << i;
}

Let’s try using both of the functions together to see how it generates a different number after every click.

Note: The standard practice is to use the return value of time(0) function as the seed.

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
srand(time(0));
int i = rand();
cout << i;
}

RELATED TAGS

rand
srand
c++
functions
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?