In article <9d**********************************@r60g2000hsc. googlegroups.com>,
Mara Guida <ma*******@gmail.comwrote:
>"Each time I run my program, I get the same sequence of numbers back
from rand()."
The answer to question 13.17, in the c-faq is:
#include <stdlib.h>
#include <time.h>
srand((unsigned int)time((time_t *)NULL));
Are all those casts in the srand() call really needed?
No. They're probably there for historical reasons.
>Is this ok, instead, relying on implicit casts when needed?
There's no such thing as an "implicit cast"; a cast is a source code
construct (and therefore inherently explicit) that forces a
conversion.
That nitpick aside, assuming you meant "implicit conversion", the
answer to your question is yes, it's perfectly valid.
>#include <stdlib.h>
#include <time.h>
srand(time(NULL));
/* or even
srand(time(0));
*/
If you forgot to #include <time.h>, you won't have a prototype in scope
for time(), and these would pass an integer 0 (or possibly a null void *)
instead of a null time_t *. Pre-ANSI C would have required a cast here
to force the right type to be passed, but now that we have prototypes
(and have for almost two decades) the correct solution is to
#include <time.hand let the compiler do the conversion for you.
Casting the return value is slightly less useless, but only slightly;
time_t (which time() returns) is required to be an arithmetic type, and
every arithmetic type can be converted to unsigned without a cast, but
your compiler might warn about some of them and the cast will tell it
to be quiet (which is in general not such a good idea, but is probably
valid here).
dave