why random number have to use header time.h?

hey guys, like my title above, why random number have to use header #include time.h? and i always found syntax srand(time(0)); can you explain to me about this syntax? ty ^^
No, it has not. But to provide a unique sequence of random numbers usually a current time is used as a seed.
It uses the value returned by the time function as the initial seed for the random number generator. Thus if you run the same program more than once it is almost certain that the time function will return different values each time and so the sequence of random numbers generated will be different on each run.
What vlad said.

Technically, you can simply do srand(0). You would get a random series of numbers, but the numbers will be the same for each run. Sometimes, that's what you want; other times, it's not. If you have to ask, it probably doesn't matter.

[edit]

And if it doesn't matter, it's probably safer to use time(0) as seed.
Last edited on
It doesn't have to be the current time: you may see std::random_device used in modern C++ programs, you may see code that reads from /dev/urandom on Linux, you may encounter a call to RAND_egd() in code that links with openSSL, you may see code that calls QueryPerformanceCounter() on Windows etc.

The goal is to come up with a number that's not the same every time the program runs. std::time(0) is just one of the many ways to do that. It's common because it has been around since the early days of C.
Last edited on
Topic archived. No new replies allowed.