srand(time(0));
Possible loss of data?
Started by PixelOp, Mar 08 2005 11:52 AM
4 replies to this topic
#1 Members - Reputation: 103
Posted 08 March 2005 - 11:52 AM
Hey guys,
Whenever I use this piece of code:
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!
Sponsor:
#2 Staff Emeritus - Reputation: 1821
Posted 08 March 2005 - 11:56 AM
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:
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));
#3 Members - Reputation: 850
Posted 08 March 2005 - 11:58 AM
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.
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.
#4 Members - Reputation: 3329
Posted 08 March 2005 - 12:00 PM
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?
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?






