Sign in to follow this  
sheep19

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

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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..

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this