I'm currently reading a beginner book on C++ and it has this example:
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int randomNumber = rand(); //generate random number
int die = (randomNumber % 6) + 1; // get a number between 1 and 6
cout << "You rolled a " << die << endl;
return 0;
}
I just want to know the purpose of the cast. I tried
cout << time(0);
and
cout << static_cast<unsigned int>(time(0));
it produces the same result so I'm not sure why the cast in the code.
The type returned by std::time which std::time_t is an implementation defined numeric type.
Numeric types are implicitly convertible to each other, so srand(time(0)); is guaranteed to be well defined, but on some implementation, std::time_t could be a type whose all values are not representable by unsigned int, so a helpful compiler might produce a warning about a narrowing conversion that might be have been accidental.
The explicit static cast tells the compiler that a conversion is intentional, so no warning would be produced regardless of how std::time_t is defind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With