Jump to content
  • Advertisement
Sign in to follow this  
SeeForever

[C++] Curious problem with rand()

This topic is 2140 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

 

Often, If you use static initialization on a global level, you can't tell which order the objects are created in.

Usage of rand() here may cause code invoking rand() in a different order than expected.

Of course, if the same build is causing different sequences, that's a different thing ohmy.png.

 

(Also, i must agree with Mir, stl http://www.cplusplus.com/reference/random/ is really sweet - I use it a lot.)

What do you mean by "static initialization on a global level"? Like initializing global variables outside of a function? I avoid doing that. tongue.png

 

Yeah, sort of. Even if you do something neat like only having one, or very few of them, it can hurt;

It's really more of a linking issue than it is a design issue, - but I suppose by sticking to pure functional programming and no static classes, it's doable.

Edited by SuperVGA

Share this post


Link to post
Share on other sites
Advertisement

You should use the new C++11 random header instead of rand; it solves this problem, and gives you better guarantees about uniform results.

I've looked into that. It's a but too hardcore for my current needs.

It's true that it's got more boilerplate than rand(), but it's also better designed and solves your problem permanently, because you're using a local variable instead of having global state. It's the same design principle you use in your own code (hopefully). And it's part of the standard, so it's not like there's the downside of linking a third party library. So you should learn to use it once, and use it for random numbers forever in C++.

For how to use it check out this talk by Stephan T. Lavavej

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!