0

I have been doing the c++ course in codecademy and there have been a few example codes that they have shown that use "srand the (time(NULL))" command to help generate random numbers but it never fully explains how the code works. I am 54% into the course and wanted to know if this is something I should know and if it has any other use besides generating random numbers. Thanks in advance for any help or advice!

1 Answers1

3

srand expects a seed (a number from which it will generate random numbers from). If you pass it the same number, it'll generate the same sequence of random numbers. If you want a different sequence of random numbers, you need to pass it a different seed. Since time is something that always changes when you run the program, you can use time(NULL) to get the current time to use as a seed.

As other has said, there are better ways to generate random numbers that you should look up if you're interested. If you're just developing on your own and only need an okay random sequence without any threading, this way works fine.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
  • Note that, because the `time` function is pretty low resolution (typically, it has one second intervals), calling `time(NULL)` in quick succession will return the same number, so that it is *not* really a safe way to get a 'random' seed. – Adrian Mole Apr 19 '20 at 18:23
  • @AdrianMole: Since you only need one seed, it works fine. – Mooing Duck Apr 19 '20 at 18:26
  • Thanks! I am learning for my own benefit but will look into more efficient ways to develop random numbers. Thank you for the help! – Jeffrey Michaelson Apr 19 '20 at 18:29
  • @MooingDuck However, if you have, for example, an array of class objects, in which each is expected to provide a *different* random sequence, then declaring and initializing them all with constructor calls of the form `object[i] = new Object(time(NULL));`, then you're likely to get all (or most) of them with the same seed. But it's fine for a once-per-program seed, I agree. – Adrian Mole Apr 19 '20 at 18:31
  • @AdrianMole: `srand` only supports one sequence per thread. If you're doing anything else, you need to manage the sequences yourself anyway, or use a smarter library. – Mooing Duck Apr 19 '20 at 21:14