Search code examples
c++compiler-warnings

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 codepad.org 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!


Solution

  • "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(nullptr))); 
    

    Given that it's now 2017, I'm editing this question to suggest that you consider the features provided by std::chrono::* defined in <chrono> as a part of C++11. Does your favorite compiler provide C++11? If not, it really should!

    To get the current time, you should use:

    #include <chrono>
    
    void f() {
        const std::chrono::time_point current_time = std::chrono::system_clock::now();
    }
    

    Why should I bother with this when time() works?

    IMO, just one reason is enough: clear, explicit types. When you deal with large programs among big enough teams, knowing whether the values passed around represent time intervals or "absolute" times, and what magnitudes is critical. With std::chrono you can design interfaces and data structures that are portable and skip out on the is-that-timeout-a-deadline-or-milliseconds-from-now-or-wait-was-it-seconds blues.