Possible loss of data?

Started by
3 comments, last by PixelOp 19 years, 1 month ago
Hey guys, Whenever I use this piece of code:
srand(time(0));

I always get this error: : warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data Could anyone explain to me exactly what it means? Thanks!
-PixelOp
Advertisement
I would guess that if you track down the definition of the type time_t, it's defined as a long (or unsigned long). On some systems, longs are larger types than ints, so when you try moving a value from one type to the other, part of it has to be thrown away.

In this particular case, it doesn't matter - all you want is some unpredicatable value to start the random number generator with. If you want to silence the warning:
srand((unsigned int)time(0));

Richard "Superpig" Fine - saving pigs from untimely fates - Microsoft DirectX MVP 2006/2007/2008/2009
"Shaders are not meant to do everything. Of course you can try to use it for everything, but it's like playing football using cabbage." - MickeyMouse

It simply means that the type time_t (returned by time) isn't guaranteed to be equivalent to a normal int variable.
In this case a loss of precision wouldn't cause any harm but in others it might, especially when writing portable code. The "solution" is to cast the return time into a basic integer.
srand((unsigned) time(0));
The time_t type could correspond to any arithmetic type. And sending, for example, a floating point value to a function receiving an integer without explicitly casting it down is seen by the compiler as a potential source of bugs.
time(0) returns a time_t.
srand() takes an unsigned int.

The compiler is nice and auto-converts from time_t to unsigned int. The warning comes that a time_t isn't an unsigned int and has different maximums/minimums. So what happens if the time_t is greater than the unsigned int's maximum?

Ahh, I was trying to mess around with the unsigned a bit but couldn't quite put it in the right place.

Thanks a lot guys!
-PixelOp

This topic is closed to new replies.

Advertisement