Sign in to follow this  

Possible loss of data?

This topic is 4664 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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));

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites

This topic is 4664 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this