5

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.

MicroVirus
  • 5,324
  • 2
  • 28
  • 53
  • An arithmetic type can be converted to an `unsigned int` using one or more of the standard conversion rules. – R Sahu Apr 21 '15 at 21:09
  • Considering that `rand` is in the process of being deprecated in favor of the new `` header, I wouldn't lose any sleep over this. – LB-- Apr 21 '15 at 21:13

1 Answers1

4

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

Community
  • 1
  • 1
Brian Bi
  • 111,498
  • 10
  • 176
  • 312