What's the difference between these? (didnt have space)

Started by
2 comments, last by sheep19 16 years, 4 months ago
What's the difference between srand (static_cast <unsigned int> (time(NULL))); and srand(time(0)); ? I'm asking because when I tried to use the latter, I got a warning, but didn't on the former (!). Also, which one should I use and when? Thanks in advance, sheep19.
Advertisement
The exact text of the warning should tell you what you need to know. In the first version, you pass srand() an unsigned int, the type it expects. In the second, you pass it a time_t value. Being a weakly typed language, the compiler will let you substitute the two types, but it will give you a warning.
An explicit cast tells the compiler that you intend to convert from one type to another. A lack of an explicit cast means there is a chance you accidentally did the wrong thing, so the compiler warns you. In this case I don't think there would be any practical difference. srand() expects an unsigned integer, and time() returns a time_t. Therefore you should explicitly cast it.

Oh, and the NULL and the zero make no real difference. C++ purists prefer the zero because I believe it is the option that is guaranteed to work, but arguably the NULL is a de-facto standard that is easier to read and arguably has better semantics. Take your pick.
When I made a game some months ago, I had to use (static_cast <unsigned int> (time(NULL))); because srand(time(0)) was making runtime errors..

This topic is closed to new replies.

Advertisement