rand() and srand() in C++ (original) (raw)

Last Updated : 22 May, 2026

rand() and srand() are commonly used in C++ for generating random numbers in programs. They help create different numeric values that are useful in games, simulations, testing, and many real-world applications.

rand() Function

The rand() function is defined in the <cstdlib> or <stdlib.h> header file and is used to generate random numbers.

Syntax

int rand()

C++ `

#include <bits/stdc++.h> using namespace std;

int main() { for (int i = 0; i < 3; i++)

    // Generate random numbers
    cout << rand() << endl;
return 0;

}

`

Output

1804289383 846930886 1681692777

srand() Function

The srand() function is used to initialize the seed value for the random number generator. Without srand(), the rand() function generates the same sequence of numbers every time the program runs.

Syntax

void srand(unsigned int seed);

#include <bits/stdc++.h> using namespace std;

int main() {

// Use current time as seed for random generator
srand(time(0));
for (int i = 0; i < 3; i++)
    cout << rand() << endl;
return 0;

}

`

Output

582797172 409020522 244217599

Random Numbers

Modern C++ introduced the library in C++11 to provide better, safer, and more reliable random number generation compared to the traditional rand() function.

Limitations of rand()

The traditional rand() function has several limitations:

Advantages of <random> Library

The <random> library provides more advanced random number generators.

Common Engine in Modern C++

The mt19937 engine is one of the most commonly used random number generators in modern C++.

C++ `

#include #include using namespace std;

int main() {

random_device rd;
mt19937 gen(rd());

cout << gen() << endl;

return 0;

}

`

Applications of rand()

The rand() function is widely used in various programming applications.

rand() vs Modern Random Library

The following table compares rand() with the modern <random> library:

Feature rand() Library
Introduced In C Language C++11
Randomness Quality Basic High
Distribution Support Limited Multiple distributions
Deterministic Output Yes Yes (with better control)
Recommended for Modern Apps No Yes
Ease of Use Simple More flexible