Okay, first of all
srand. As a tangent, I think that a good tutorial for random numbers would be to show the user how to implement their own pseudo-random number generator. Except I've never done it myself, so anything I implement will likely be pretty sucky in terms of distribution. End tangent.
How random number generators tend to work is, they take the last random value generated, perform a couple of math operations on it, and then spit out that new value as the next number in the list. The problem comes from the fact that if you start with the same value then every subsequent value will always be the same each time you run the program. It's like if someone says "pick a number" and then they give a set of steps like "add 3, divide by two, XOR that with 0xF3A002EB, then subtract 7" then you'll always get the same value if you always pick the same number.
This is where
srand comes in, in relation to
rand. All you do is give
srand a different number each time you run the program and then the problem mentioned in the last paragraph won't happen! But this brings us a new problem: how to give
srand a different number each time the program runs? We can't use a random number, because that's like a chicken and the egg type problem that we're still trying to solve.
This is where
time comes in. If you can find a way to pick a different number at the start then you'll get a different answer. And what number is different every time you run the program? The time!
This leads me to your second query concerning the
time function. Let's take a look at some
documentation , shall we?
It says, basically, that you
can pass a pointer to a
time_t object (I'm pretty sure it's just a typedef for a large integer type) and it will fill that location in memory with the data. And time also returns a
time_t object or -1 on error.
"Why does it do this?" I asked myself. After thinking about it, I decided the most likely reason was that you could then use the time function's return value as error checking. You could do something like:
time_t currentTime;if( time(¤tTime) == -1){ std::cout << "Could not retrieve time." <<std::endl; // do some error handling or something}
I could be wrong, I've never used it that way. And who ever heard of
time failing?
Hope that help.s