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.
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.
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).
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) .
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() !
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With