What does srand actually do?

Ok, so I understand how srand works. It creates an ever changing 'starting point' for the rand function to produce a 'random number' that will be different each time the program runs. My question is what does the srand actually DO? I guess I am just confused how srand can affect rand without anything being passed into rand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    unsigned seed = time(0);

    srand(seed);

    cout << rand() << endl;
    
    return 0;
}
srand() is the algorithm for generating pseudo random numbers. The seed is what determines the "starting point". time() calls the system time so that the seed is different every time, unless you happen to call it at the exact time on a different day.

An overly simplified version of generating random numbers might be like a wheel (think Wheel of Fortune) with different numbers at each tick. The seed determines the starting point and then it stops at every 5th tick each successive call. That is why if you set the seed to a constant, you will get the same series of numbers every time.

A little more in depth explanation:
http://www.learncpp.com/cpp-tutorial/59-random-number-generation/
Last edited on
Topic archived. No new replies allowed.