How to Generate Random Numbers in C++

How-to basics · Updated November 23, 2026

Generating random numbers in C++ is a common task for games, simulations, and testing. The modern approach uses the <random> header, which provides better distribution and control than the old rand() function. This guide shows you how to create random integers and floating-point numbers, seed the generator properly, and avoid common pitfalls. You’ll need a C++11 or later compiler (most modern ones support it).

What You’ll Need

  • A C++ compiler that supports C++11 or later (e.g., GCC, Clang, MSVC).
  • A text editor or IDE (Visual Studio, Code::Blocks, VS Code, etc.).
  • Basic familiarity with compiling and running C++ programs.

Step-by-Step

  1. Include the necessary headers.

    At the top of your file, add #include <random> for the random number facilities and #include <iostream> if you want to print results. For example:

    #include <random>
    #include <iostream>
  2. Create a random engine.

    Choose a random number engine. The most common is std::mt19937 (Mersenne Twister). Declare it like this:

    std::mt19937 gen;

    This engine will produce a sequence of pseudo-random numbers. You can also use std::default_random_engine, but mt19937 is preferred for quality.

  3. Seed the engine.

    Without seeding, the engine starts with the same default state every run, giving identical numbers. Seed it with a truly random value, typically from a hardware device. Use std::random_device:

    std::random_device rd;
    std::mt19937 gen(rd());

    This initializes the engine with a seed from rd(). If you want reproducible results (e.g., for debugging), you can seed with a fixed number like std::mt19937 gen(42);.

  4. Define a distribution.

    Engines produce raw unsigned integers, but you usually want numbers in a specific range. Use a distribution object. For integers, use std::uniform_int_distribution. For example, to get integers between 1 and 10:

    std::uniform_int_distribution<int> dist(1, 10);

    For floating-point numbers, use std::uniform_real_distribution:

    std::uniform_real_distribution<double> distReal(0.0, 1.0);
  5. Generate a random number.

    Call the distribution with the engine as an argument. The distribution returns a random number in the specified range. For example:

    int randomInt = dist(gen);
    double randomDouble = distReal(gen);

    Each call to dist(gen) produces a new number.

  6. Put it all together in a complete program.

    Here’s a full example that prints 5 random integers between 1 and 100:

    #include <iostream>
    #include <random>
    
    int main() {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<int> dist(1, 100);
    
        for (int i = 0; i < 5; ++i) {
            std::cout << dist(gen) << " ";
        }
        std::cout << std::endl;
        return 0;
    }

    Compile and run it. You should see five different integers each time you run the program.

Common Mistakes

  • Using rand() and srand() – These are legacy C functions and often produce poor-quality randomness. Stick with <random>.
  • Seeding inside a loop – If you create and seed the engine inside a loop, you may get the same number repeatedly, especially if the loop runs fast. Seed once before the loop.
  • Using std::random_device as the only engine – std::random_device is meant for seeding, not for generating large sequences. It may be slow or even deterministic on some platforms.
  • Forgetting to include <random> – This causes a compilation error. Always include it.
  • Assuming uniform_real_distribution includes the upper bound – It generates numbers in the range [a, b), meaning b is never included. If you need b included, adjust the range or use a different approach.

Tips

  • Use auto for brevity – You can write auto gen = std::mt19937(rd()); to avoid spelling out the type.
  • For reproducible results – Use a fixed seed (e.g., std::mt19937 gen(123);) when you need to debug or compare runs.
  • For cryptographic security – The <random> library is not cryptographically secure. Use a library like OpenSSL or the platform’s CSPRNG for security-sensitive applications.
  • Shuffle containers – Use std::shuffle from <algorithm> with your engine to randomly reorder elements in a vector or array.
  • Performance – Creating a distribution object is cheap, but creating an engine is relatively expensive. Reuse the engine across many calls.

Troubleshooting

  • I get the same numbers every run. – You’re not seeding the engine properly. Make sure you use std::random_device to seed, or seed with a changing value like the current time (though time-based seeds are predictable).
  • Compilation error: ‘random’ file not found. – Your compiler may not support C++11. Enable C++11 or later with a flag like -std=c++11 (GCC/Clang) or set the language standard in your IDE.
  • Numbers are not uniformly distributed. – If you use rand() % n, you get modulo bias. Using uniform_int_distribution avoids this. Also, ensure you’re not using a poor engine like std::minstd_rand for critical applications.
  • Getting negative numbers unexpectedly. – If you use uniform_int_distribution with negative bounds, that’s fine. But if you use std::mt19937 directly, it returns unsigned values, which can be large. Always use a distribution.
  • Random device is slow or blocks. – On some systems, std::random_device may block until enough entropy is available. If this is a problem, you can seed from a time-based seed, but be aware of predictability.

Frequently Asked Questions

Can I still use rand() in C++?

Yes, but it’s not recommended. rand() has poor distribution and is implementation-dependent. The <random> library is more flexible and reliable.

How do I generate a random boolean (true/false)?

Use std::uniform_int_distribution<int> dist(0, 1); and treat 1 as true, or use std::bernoulli_distribution which returns true with a given probability (default 0.5).

How do I generate a random number between 0 and 1?

Use std::uniform_real_distribution<double> dist(0.0, 1.0);. This gives a double in [0, 1).

Why do I get the same sequence if I don’t seed?

Because the engine starts with a fixed default seed. Seeding with std::random_device gives a different seed each run, producing different sequences.

Can I use random numbers in multithreaded programs?

Yes, but each thread should have its own engine and distribution to avoid data races. Sharing a single engine across threads requires synchronization, which slows things down.

How do I pick a random element from a vector?

Generate a random index with std::uniform_int_distribution<size_t> dist(0, vec.size() - 1); and then access vec[dist(gen)]. Alternatively, use std::sample from C++17.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.