Ioannis Vranos <> writes:
> Ben Pfaff wrote:
>> (Richard Bos) writes:
>>
>>> Ioannis Vranos <> wrote:
>>>> Richard Bos wrote:
>>>>> Ioannis Vranos <> wrote:
>>>>>> Is srand(time(NULL)); an effective solution for seeding rand(),
>>>>> Unless your time_t is a floating point type
>>>> The function prototype of srand() is
>>>>
>>>> void srand(unsigned int seed);
>>>>
>>>> Whatever time_t is, isn't there an implicit conversion to unsigned?
>>> Yes. But the conversion of a floating point value to an integral type
>>> causes UB if that value, rounded down, would not fit into the integral
>>> type - even if it's an unsigned type.
>>
>> Additionally, a floating point time value may not be useful as a
>> random seed, for example if the time value is always between 0
>> and 1. (I am not aware of any systems that do this.)
>
> Also I assume in the floating point case, casting to unsigned is
> needless, right?
Correct; the conversion is implicit for any arithmetic type (which
time_t is guaranteed to be). If time_t is a floating-point type, then
other problems appear: if the result of time() doesn't vary outside a
small range, then you won't get much variation in seed values, and if
it can go outside the range 0 .. UINT_MAX, the behavior of the
conversion can be undefined.
In theory, you could even have problems with an integer time_t.
Imagine that unsigned int is 32 bits, and time_t is a 64-bit integer
type whose high-order 32 bits represent time in seconds and whose
low-order 32 bits represent fractions of a second. Imagine further
that the underlying system clock can only represent whole seconds, so
the low-order 32 bits are always 0. Then converting *any* time_t
value returned by time() to unsigned int will yield 0.
Ben Pfaff's solution (treating the time_t result as an array of
unsigned char and hashing it) avoids all these problems, none of which
are likely but all of which are allowed by the standard.
In practice, using srand(time(NULL)) is likely to be good enough for a
quick-and-dirty program, and is unlikely to break in any of the above
described ways on any system you're likely to run into in real life.
On the other hand, the implementation-provided rand() function is
typically not very good; if you want *good* random numbers, you should
use some other technique. <HANDWAVE>See the literature for
details.</HANDWAVE>
Incidentally, I've e-mailed Steve Summit (the FAQ maintainer) about this;
he says:
Say, you're right. That's a last vestige of my PDP-11/V7/K&R C
days -- I thought I'd stamped those all out.
--
Keith Thompson (The_Other_Keith) <kst->
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"