3

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.

g_b
  • 11,728
  • 9
  • 43
  • 80

2 Answers2

5

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
4

srand() expects an unsigned int and time() returns std::time_t which is an implementation defined type. It might not be unsigned but signed. The static_cast is there to suppress the possibility of an error/warning if std::time_t is defined as something else as unsigned int. Note that this isn't actually good practice.

P.S If you have a compiler that supports C++11 then stop using rand()/srand() all together and start using the new header <random>.

Community
  • 1
  • 1
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122