Why do I get a warning about a possible data loss when sowing a random number generator since time (NULL)?

am studying vectors and made some code that selects random numbers that I can use to buy lottery tickets here in the Netherlands. But, although it works, the compiler warns me of a "conversion from" time_t "to" unsigned int, possible data loss. "

Can anyone determine what causes this? I have not even defined any unsigned int in this code; int i by default is a signed int, as i understand it. Thank you for understanding.

#include <iostream> #include <vector> #include <string> #include <ctime> using namespace std; void print_numbers(); string print_color(); int main() { srand(time(NULL)); print_numbers(); string color = print_color(); cout << color << endl; system("PAUSE"); return 0; } //Fill vector with 6 random integers. // void print_numbers() { vector<int> lucky_num; for (int i = 0; i < 6; i++) { lucky_num.push_back(1 + rand() % 45); cout << lucky_num.at(i) << endl; } } //Select random color from array. // string print_color() { string colors[6] = {"red", "orange", "yellow", "blue", "green", "purple"}; int i = rand()%6; return colors[i]; } 

Exact compiler message: warning C4244: "argument": conversion from "time_t" to "unsigned int", possible data loss. Line 11.

+4
source share
6 answers

Since time_t is larger than unsigned int on your particular platform, you get this warning. Casting from the “bigger” to the “smaller” type involves truncating and losing data, but in your particular case it does not really matter, because you just seed the random number generator and overflow the unsigned int for the date in the very distant future.

Casting to unsigned int should explicitly suppress the warning:

 srand((unsigned int) time(NULL)); 
+6
source

srand(time(NULL)); <- This line. time returns an integer of type time_t, and you convert it to unsigned int. time_t is of type unsigned [the largest possible int value].

+1
source

time_t is a 64-bit value on many platforms to prevent a temporary end to time, while unsigned int is 32 bits.

In your case, you don't care, you just sow a random number generator. But in another code, if your software ever deals with dates past 2038 , you could truncate time_t to a 32-bit date to 2038 by clicking on a 32-bit value.

0
source

time returns a time_t object.

srand expects unsigned int.

0
source
 srand(time(NULL)); 

This line may overflow if the return value from time exceeds the range of the unsigned int representation, which is certainly possible.

0
source
 void srand ( unsigned int seed ); time_t time ( time_t * timer ); typedef long int __time_t; 

long int does not match unsigned int. Hence the warning.

(from fooobar.com/questions/41067 / ...

0
source

All Articles