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.
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));
time_t
is a 64 bit value on many platforms to prevent the epoch time eventually wrapping while unsigned int
is 32 bits.
In your case, you don't care cause you're just seeding the random number generator. But in other code, if your software ever deals in dates past 2038, you could have your time_t
truncated to a 32-bit pre 2038 date when you cast to a 32-bit value.
time returns a time_t
object.
srand is expecting an unsigned int.
srand(time(NULL));
This line can overflow if the return value from time
exceeds the representation range of an unsigned int
, which is certainly possible.
void srand ( unsigned int seed );
time_t time ( time_t * timer );
typedef long int __time_t;
long int is not the same as a unsigned int. Hence the warning.
(from stackoverflow
精彩评论