rand() Considered Harmful
Why Hacker News recommends it
It is the standard reference for why rand() is broken in C++ and what to use instead.
What it is
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.
Recommended by 1 HN commenters across 1 different months, 2019 to 2025.
What Hacker News said
Recommends camel-cdr · 2022-05 · on “Show HN: A glib-like multi-platform C library”
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 literally worse than using the rand reference implementation. Also, tb_random_range uses a biased and slow implementation with modulo. (see [LINK] for the proper way to do this) I might look into adding a proper PRNG implementation, but I'll recommend a few resources: A lesson of what not to do: [this video] ("r
Cites einpoklum · 2019-08 · on “Dark Corners and Pitfalls of C++”
> 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 `<algorithm>` functions (memset vs std::fill) * Using `rand()` instead of the standard library's facilities (even though it's broken [this video] ) So... it's outdated and inelegant C++, regardless of any actual errors.
Cites slavik81 · 2025-06 · on “C++ Seeding Surprises (2015)”
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. [this video]