user2576878 user2576878 - 14 days ago 12x
C++ Question

srand (time (null)) causes compiler warning: implicit conversion loses integer precision

Apologies if this question has already been answered.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main () {

srand( time(NULL) );
cout << rand();

"implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'"

Is the error message Im getting when I execute the code above. I am using xcode 4.6.1. Now when I use a different complier such as the one from it executes perfectly fine generating what seems like random numbers so I am assuming it is an xcode issue that I need to work around?

I have JUST started programming so I am a complete beginner when it comes to this. Is there a problem with my code or is it my complier?

Any help would be appreciated!


"implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'"

You're losing precision implicitly because time() returns a long which is larger than an unsigned int on your target. In order to workaround this problem, you should explicitly cast the result (thus removing the "implicit precision loss"):

srand( static_cast<unsigned int>(time(NULL)));