A Guide to C++ : Why It's Better Than rand()

2025-09-22

Many programmers start with the old C-style rand() function. While it seems simple, it has some major issues.

A classic mistake is to use rand() without properly seeding it. The rand() function generates a sequence of "random" numbers based on a seed. If you don't provide one, it uses a default seed (usually 1), which means you'll get the exact same sequence of numbers every time you run your program. This is great for debugging but terrible for actual randomness.

Here's an example of this common mistake

#include <iostream>
#include <cstdlib>

int main() {
    // This will produce the same output every time!
    std::cout << rand() << std::endl;
    std::cout << rand() << std::endl;
    return 0;
}

Even if you seed it, using time(NULL) as the seed can still be problematic if you run the program multiple times within the same second, as it will use the same seed value.

Another common issue is trying to get a number within a specific range using the modulo operator (%) with rand(). For example, rand() % 100 to get a number between 0 and 99. The problem here is that the distribution of numbers won't be uniform, especially for small ranges. The numbers will be slightly skewed.

The C++ <random> library is the modern, powerful, and correct way to handle pseudo-random number generation. It's a bit more involved than rand(), but it gives you much better control and quality.

To generate a random number with <random>, you need three things

A random number generator
This is the engine that produces the numbers. A good choice is std::mt19937, which is a Mersenne Twister engine. It's fast and provides high-quality randomness.

A seed
Just like with rand(), you need to seed your engine. The best practice is to use std::random_device to get a truly non-deterministic seed from the operating system.

A distribution
This is what makes sure your numbers are in the range you want and have the correct statistical properties (like being uniform). std::uniform_int_distribution is perfect for integers.

Here's how to generate a random integer between 1 and 100 using the correct modern approach.

#include <iostream>
#include <random>

int main() {
    // 1. Get a random seed from the operating system
    std::random_device rd;

    // 2. Use the seed to initialize the Mersenne Twister engine
    std::mt19937 gen(rd());

    // 3. Define the distribution: 1 to 100 (inclusive)
    std::uniform_int_distribution<> distrib(1, 100);

    // Now, let's generate some numbers!
    std::cout << "A random number between 1 and 100: " << distrib(gen) << std::endl;
    std::cout << "Another one: " << distrib(gen) << std::endl;

    return 0;
}

This code is much better because

It uses a truly random seed from std::random_device, so you get a different sequence of numbers every time.

The std::uniform_int_distribution ensures the numbers are uniformly distributed within the specified range, so there's no statistical bias.

The <random> library isn't just for integers. You can generate random numbers that follow different statistical patterns, which is super useful for simulations and scientific applications.

std::uniform_real_distribution
For floating-point numbers in a range (e.g., between 0.0 and 1.0).

std::normal_distribution
For numbers that follow a bell curve, also known as a Gaussian distribution. This is great for modeling real-world data like height or test scores.


cpp



C++ Unordered Sets: empty() vs. size() == 0

The std::unordered_set::empty() method is a straightforward way to check if an std::unordered_set is empty. It returns a boolean value true if the set contains no elements


Understanding and Using C++ Complex Number Literals: Tips and Tricks

Let's break down what these operators do, the problems you might run into, and how you can handle them.In short, these operators allow you to create complex number literals directly in your code


C++20's tai_clock: Pitfalls, Conversions, and Alternatives to International Atomic Time

Let's dive into std::chrono::tai_clock!The std::chrono::tai_clock is a C++20 standard library clock that represents International Atomic Time (TAI)



C++ Low-Level Memory Management: Common Issues & Safer Alternatives

In C++, low-level memory management refers to directly allocating and deallocating memory using functions like new and delete or their C-style counterparts


Avoiding std::string Pitfalls: Safer Indexing and Efficient Concatenation

Here's a friendly breakdown of common issues, along with alternative sample code in English.The biggest source of trouble is often the interoperation between the modern C++ std::string and the older C-style character arrays (char* or const char*)


Troubleshooting std::chrono::tai_time Stream Operator

This is a common point of confusion for developers and is a limitation of the current C++ standard library. It's an oversight that requires developers to manually format the output


C++ Stream Buffers: Common Pitfalls and Alternatives to operator=

The std::basic_streambuf class is the unsung hero behind C++ I/O streams like std::cin, std::cout, and file streams. It's an abstract base class that manages the actual I/O operations—reading from and writing to a sequence of characters


Ditching Mutexes: How to Use osyncstream for Interleaved-Free Output

The std::basic_syncbuf and its destructor, std::basic_syncbuf::~basic_syncbuf(), are part of C++20's synchronized output streams library (<syncstream>), which is all about making output thread-safe


C++ std::memchr() vs. std::string::find() Explained

std::memchr is a function from the <cstring> header, designed to work with raw memory blocks, not C++ std::string objects


A Guide to C++ std::mdspan::stride: Avoiding Common Pitfalls

Simply put, the stride tells you how far apart elements are in a specific dimension. Think of a 2D array, array[row][col]. To get to the next column