Confusing line.

Okay so can somebody explain this line of code to me? I am just learning c++ still and i am just a bit confused on what this means

1
2
3
4
#include <ctime>
#include <cstdlib>

srand(static_cast<unsigned int(time (0))); //seed random number generator 



I know this doesnt the code is an error i was just showing a little snippet and a the files that i included.
Could you like explain the concept of current time?
Well that code is missing a > after the int. But anyways...


The time function is explain in detail here:

http://www.cplusplus.com/reference/ctime/time/


Basically it returns current time in seconds since the epoch (typically Jan 1, 1970... but it may vary depending on implementation). The is passing a null pointer for the parameter to time() since we don't need it.

So that explains what time(0) is doing. That chunk returns a time_t with the current time.

That time_t value is then put in a static_cast which converts it from a time_t to a unsigned int

So that explains static_cast<unsigned int>(time(0)) ... it's the current time as an unsigned int.

That time is then passed to srand, which takes an unsigned int as its parameter.

srand is explained in detail here:
http://www.cplusplus.com/reference/cstdlib/srand/

But basically what it does is "seeds" (or "initializes") the random number generator used by rand(). rand() does not actually generate random numbers... but rather uses a mathematical formula to produce a sequence of numbers which appear random. The 'seed' determines where it starts in that sequence.


So by seeding with the current time... you are ensuring that you get a different sequence of random numbers each time the program is started (unless the program is started multiple times in the same second... in which case time() will give you the same time and you'll get the same seed and therefore the same random sequence).



TL;DR

It seeds rand so you don't get the same numbers every time you run the program.
Topic archived. No new replies allowed.