rand() Considered Harmful
aghuttun1 HN recommenders · 2019–2025
16K views · talk · evergreen · Uploaded 2013-09-18
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.
It is the standard reference for why rand() is broken in C++ and what to use instead.
1:12:27CppCon 2015: Andrei Alexandrescu “std::allocator...”
CppCon
51:18Lexical Scanning in Go - Rob Pike
GoogleFOSSSydney
59:34CppCon 2017: Matt Kulukundis “Designing a Fast, Efficient, Cache-friendly Hash Table, Step by Step”
CppCon
42:30RustConf 2018 - Closing Keynote - Using Rust For Game Development by Catherine West
Rust Programming Language
1:19:52CppCon 2016: Jason Turner “Rich Code for Tiny Computers: A Simple Commodore 64 Game in C++17”
CppCon
12:04Why Being Delusional is a Superpower
Veritasium
1:55:24Ideas about a new programming language for games.
Jonathan Blow
1:27:46CppCon 2014: Mike Acton "Data-Oriented Design and C++"
CppCon
3 comments from Hacker News
> 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.
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]
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]