
rand() Considered Harmful
About this video
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 it appears in the archive
It is the standard reference for why rand() is broken in C++ and what to use instead.
AI-generated summary and labels from the source dataset; verify important details against the video. Source & credits.
From the Hacker News discussion
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: [VIDEO] ("rand() Considered Harmful") Some good modern PRNGs: [LINK] , [LINK] , [LINK] Generating random numbers in a specific range: [LINK]
Read original comment ↗> 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 [VIDEO] ) So... it's outdated and inelegant C++, regardless of any actual errors.
Read original comment ↗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]
Read original comment ↗