rand() Considered Harmful

Channel:aghuttun · Length:31:27 · Published:2013-09-18 · Views:15654

Watch on YouTube

Summary

Stephan T. Lavavej's GoingNative 2013 talk explaining why calling rand() and using rand() % 100 is bad in C++, and how the C++11 <random> header does the job properly.

Why HN recommends it

It is the standard reference for why rand() is broken in C++ and what to use instead.

recommended by Stephan T. Lavavej, maintainer of Visual Studio's C++ Standard Library, in his "rand() Considered Harmful" talk — HN, 2025

C, C++, Rust, Go & systems languages · Probability & game theory

Subtitles (excerpt)

okay hi there uh I'm Stephan T laade and today I'm going to talk about Rand the CRT function uh and what has happened to it in C plus 11 answer nothing it's not even deprecated which is kind of sad uh but there is at least a replacement functionality in C+ 11 that you should totally be using um so Rand considered harmful let me show you uh some code okay so here's a little program I wrote It's C++ even though it doesn't really look like C++ you know what wrong with this but wait you know you might be saying hey you know I bet you everything's wrong haha you know problem solved answer no there are many redeeming qualities that this code has uh for example it includes all the headers that it needs all the headers that it's including are actually needed uh they're sorted in sorted order uh the braces are delicious I mean if you don't like these braces you are wrong I'm just saying um and you know non-trivially you know percent D that that is the correct format specifier for in you know might be saying you print F kind of abomination but if you're going to use it at least get the types right and actually that expression there that's in so that's cool and I emitted the return zero and R AR I see examples coming all the

On Hacker News

Whenever I see such libraries, the first thing I check out is their PRNG implementation, and this one must be the worst I've seen so far. (The rest of the library is probably quite good, I'm just talking about the PRNG part) The library has one PRNG, and it is the following: tb_spinlock_enter(&g_lock); g_value = (g_value * 10807 + 1) & 0xffffffff; tb_spinlock_leave(&g_lock); Using this is literal… — camel-cdr, 2022-05
I used it because it was recommended by Stephan T. Lavavej, maintainer of Visual Studio's C++ Standard Library, in his "rand() Considered Harmful" talk, back when <random> was introduced. See 11m30s. [VIDEO] — slavik81, 2025-06
> Here is a short snippet of some abstract C++ code. As you can see, that is a code from the Windows DLL I stopped reading at this point. But, ok, I didn't really. I also noticed the code was quite dated / inopportune: * Has a "X-er" class - which probably shouldn't exist in the first place. * Using raw `delete` and `new` * Using unions instead of std::variant's * Using C library calls instead of… — einpoklum, 2019-08

Related videos