The VC++ Level 4 warning message means to say time_t
is a larger type than unsigned int
- probably 64 bits, so the value returned by time()
need to be truncated to 32 bits to be passed to srand()
. In this specific case it doesn't matter, but it may be an issue in other places (consider handling file size as unsigned int
just to discover that the program crashes with files >= 4 GB in size).
To silence the warning use an explicit cast which tells the compiler you know what you're doing:
srand((unsigned)time(nullptr));
Having said that, using rand() % X
is considered bad practice because it is imprecise (among other things). The value returned by rand()
is uniformly distributed between 0 and RAND_MAX
but RAND_MAX
+1 usually doesn't divide evenly by X
, which would result in a biased distribution of rand() % X
.
C++ comes with its own random number implementation which is in many ways better:
#include <iostream>
#include <random>
int main() {
std::random_device rd; // better than time()
std::mt19937_64 gen(rd()); // better than rand()
std::uniform_int_distribution<> dist(701, 1701); // better than % 1000 + 701
std::cout << dist(gen) << std::endl;
}