Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using std::time with std::srand valid code?

It is legal in C++ to write:

std::srand(std::time(nullptr));

or does this yield undefined behaviour?


std::time returns a std::time_t which is an arithmetic type, but other than that unspecified. From my understanding, arithmetic type is any of the floating point, integer and character types.

std::srand takes an unsigned int as a seed value.

Therefore, I would think that you cannot strictly perform this conversion. I read that on systems conforming to POSIX that std::time_t is integral and is the number of seconds since 00:00, Jan 1 1970 UTC. In this case, the conversion can entail converting from signed to unsigned, which is an implementation-defined conversion but should be OK, and from a larger integral to a smaller integral type which is fine too for the seed.

like image 914
MicroVirus Avatar asked Sep 29 '22 05:09

MicroVirus


People also ask

What does Srand time NULL )) do in C++?

Any other value for the seed produces a different sequence. srand(time(NULL)); makes use of the computer's internal clock to control the choice of the seed. Since time is continually changing, the seed is forever changing.

What does Srand time 0 )) do?

time(0) gives the time in seconds since the Unix epoch, which is a pretty good "unpredictable" seed (you're guaranteed your seed will be the same only once, unless you start your program multiple times within the same second).

How does Srand work in C++?

Working of C++ srand()The srand() function sets the seed for the rand() function. The seed for rand() function is 1 by default. It means that if no srand() is called before rand() , the rand() function behaves as if it was seeded with srand(1) .

How do you initialize a Srand?

The best simplest way is just to use time() : int main() { srand(time(nullptr)); ... } Be sure to do this at the beginning of your program, and not every time you call rand() !


1 Answers

You are correct, time_t may be a floating point type and if the result of truncating the value is not representable as unsigned int, then the behaviour is undefined ([conv.fpint]/1).

If you want to generate random numbers in a standard-conforming way, I suggest the C++11 <random> facilities. You can seed the RNGs from std::random_device. See, e.g., https://stackoverflow.com/a/19666713/481267

like image 56
Brian Bi Avatar answered Oct 05 '22 06:10

Brian Bi