The short answer
srand() sets the starting point for the sequence that rand() returns. Call it once, before the first call to rand(). Seeding with the current time is the common approach, because the seed changes from one second to the next. The seed must be an unsigned int, so the time value is cast to that type.
The headers
In C++, rand() and srand() come from <cstdlib>, and time() comes from <ctime>. In C, the same functions come from <stdlib.h> and <time.h>, and you call them without the std:: prefix.
The cast matters because srand takes an unsigned int. For the difference between the two types, see signed vs unsigned in c.
Seed with the current time
#include <cstdlib>
#include <ctime>
#include <iostream>
int main() {
std::srand(static_cast<unsigned int>(std::time(nullptr)));
for (int i = 0; i < 5; ++i) {
std::cout << std::rand() % 100 << '\n';
}
}
Each run starts from a seed that depends on the current second, so the numbers usually differ between runs. Runs that start in the same second get the same numbers.
The mistake: calling srand inside a loop
for (int i = 0; i < 5; ++i) {
std::srand(static_cast<unsigned int>(std::time(nullptr))); // resets the sequence every pass
std::cout << std::rand() % 100 << '\n'; // often the same number 5 times
}
Within one second, every pass sets the same seed, and the first value after a given seed is always the same. The result is often the same number printed five times. Move srand before the loop.
Repeatable sequences with a fixed seed
For a repeatable sequence, pass a fixed number:
std::srand(42); // the same seed gives the same sequence on the same system
This is useful for reproducing a bug or checking a simulation. Do not use a fixed seed where the numbers should differ between runs.
The same idea in C
In C the code looks almost the same, without std:::
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand((unsigned int)time(NULL));
printf("%d\n", rand() % 100);
return 0;
}
Common mistakes
- Never seeding. Without
srand, the sequence starts from the default seed and repeats every run. - Seeding in a loop. See the section above.
- Calling srand again partway through. That restarts the sequence, so later values can repeat ones you already used.
- Using the time as a secret. The time is predictable, so do not rely on it for passwords or keys. For why, see is rand() actually random.
Where to go next
For the broader picture, including the newer <random> header, see how to generate random numbers in c. For a shorter introduction to the basic call, see how to use rand().