Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a warning about possible loss of data when seeding the random number generator from time(NULL)?

am learning vectors and made a bit of code that selects random numbers i can use for buying lottery tickets here in Netherlands. But although it runs, the compiler is warning me about 'conversion from 'time_t' to 'unsigned int, possible loss of data'.

Can anyone spot what is causing this? I haven't even defined any unsigned int in this code; int i by default is a signed int as i understand. Thanks for insight.

#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 loss of data. Line 11.

like image 684
Daniel Gratz Avatar asked Oct 03 '11 13:10

Daniel Gratz


1 Answers

Because time_t happens to be larger in size than unsigned int on your particular platform, you get such a warning. Casting from a "larger" to a "smaller" type involves truncating and loss of data, but in your particular case it doesn't matter so much because you are just seeding the random number generator and overflowing an unsigned int should occur for a date in the very far future.

Casting it to unsigned int explicitly should suppress the warning:

srand((unsigned int) time(NULL));
like image 57
Blagovest Buyukliev Avatar answered Sep 22 '22 16:09

Blagovest Buyukliev