>srand((unsigned int)time((time_t *)NULL));
FYI, because this came up recently. Neither of those casts are necessary, except possibly to silence warnings in the case of casting time.
1) There's no need to cast NULL to (time_t*) because NULL is a generic null pointer type. It's always implicitly convertible to an object pointer type. That gives you this:
Code:
srand ( (unsigned)time ( NULL ) );
2) There's no need to cast time because time_t is an arithmetic type. It'll be implicitly converted to unsigned int with or without the cast. However, the conversion may not be benign, and compilers may warn about it. You should heed this warning, because if time_t has a type and value that isn't representable as unsigned int, the behavior of this conversion is undefined. Removing the cast gives you this:
Code:
srand ( time ( NULL ) );
Much simpler, but still non-portable. You can still use the current time with a little more work to avoid the overflow issue:
Code:
double diff = difftime ( 0, time ( NULL ) );
double sec = fmod ( diff, UINT_MAX + 1.0 );
srand ( (unsigned)sec );
But this bounds you to getting a new seed only once per second and the cast is still likely to be needed for a clean compile (loss of precision warnings from double to unsigned int).
Another option is to hash the time_t in such a way that you don't rely on its representation or have to worry about overflow errors on conversion:
Code:
unsigned hash ( void *key, size_t len )
{
unsigned char *p = key;
unsigned h = 0;
size_t i;
for ( i = 0; i < len; i++ )
h = 33 * h ^ p[i];
return h;
}
time_t now = time ( NULL );
srand ( hash ( &now, sizeof now ) );