srand() seeds the pseudo-random number generator used by rand() . If rand() is used before any calls to srand() , rand() behaves as if it was seeded with srand(1) . Each time rand() is seeded with srand() , it must produce the same sequence of values.
To continue with the deck of cards analogy. Every time you call rand you just get the next “random” number by taking a card off the top of the deck, reading it, then putting it at the bottom. So without seeding rand you’ll always be using a pre-shuffled deck of cards that’s in the same order e.g.
Ace of Clubs → Two of Clubs → Three of Clubs
And if you restart the program you will get the exact same sequence.
For testing purposes using a known seed (e.g. srand(3)) is great as it makes testing far easier. However it makes for a terrible random number generator afterwards.
time is a function from C
Returns the current calendar time encoded as a std::time_t object, and also stores it in the object pointed to by arg , unless arg is a null pointer.
In practice that is the number of seconds since January 1st 1970. So with that, every time you run the program you would be seeding rand with a different number… unless you manage to run the program multiple times within the same second.
rand actually does not “randomize” or randomly choose a number from a given set, but every time it s called, it exactly chooses same numbers. In order to make it generate random numbers, we need to change the set it uses every time (or shuffle the same set), and that’s what srand does.
So we have to use rand in conjunction with srand to get real randomized outcome and we use time of day (in seconds) to get different seed numbers to put a shuffled deck in front of rand.