1

I have int r_number = 0; as a global variable.

In the code below:

        srand(time(0));
        r_number = rand() % 1000 + 701;

It keep spamming this warnings:

1>: warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data

Whats wrong in the conversion?

  • 2
    Don't use C's random library. Use C++ random library. See https://stackoverflow.com/questions/52869166/why-is-the-use-of-rand-considered-bad/52869953 to see why – bolov Feb 13 '21 at 11:25
  • You can just add a cast to silence this warning: `srand((unsigned int)time(0));` – Paul R Feb 13 '21 at 11:26

1 Answers1

1

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;
}
rustyx
  • 80,671
  • 25
  • 200
  • 267