How to Generate Random Numbers in C++

How-to basics · Updated November 23, 2026

To generate random numbers in C++, you use the <random> header, which provides modern, flexible, and statistically sound generators. The basic pattern is: create a random engine (like std::mt19937), seed it with a random device, then use a distribution (like std::uniform_int_distribution) to get numbers in your desired range. This replaces the old C-style rand() and srand(), which are less reliable and harder to control.

What You’ll Need

  • A C++ compiler that supports C++11 or later (most modern compilers do, e.g., GCC, Clang, MSVC).
  • A text editor or IDE (Visual Studio, Code::Blocks, CLion, or just a plain editor with command-line compilation).
  • Basic familiarity with compiling and running a C++ program.

Step-by-Step

  1. Include the necessary headers. Add #include <iostream> for output and #include <random> for random number generation.
  2. Create a random device. This is a source of true randomness (like hardware entropy). Declare: std::random_device rd;. This will be used to seed the engine.
  3. Create a random engine. The most common is std::mt19937 (Mersenne Twister). Seed it with the random device: std::mt19937 gen(rd());. This engine generates raw random bits.
  4. Define a distribution. This converts the engine’s output into numbers you want. For integers, use std::uniform_int_distribution<int> dist(1, 100); to get numbers between 1 and 100 inclusive. For doubles, use std::uniform_real_distribution<double> dist(0.0, 1.0);.
  5. Generate a random number. Call the distribution with the engine as an argument: int random_number = dist(gen);. Each call gives a new random value.
  6. Put it all together. Here’s a complete example that prints 10 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 < 10; ++i) {
        std::cout << dist(gen) << " ";
    }
    std::cout << std::endl;
    return 0;
}

Compile and run. You should see 10 different numbers each time you run the program.

Common Mistakes

  • Using rand() without seeding. If you call rand() without srand(), you get the same sequence every run. Even with seeding, the quality is poor.
  • Seeding with a constant. Using std::mt19937 gen(42); always gives the same sequence. That’s fine for debugging, but not for real randomness.
  • Creating a new engine inside a loop. If you create the engine and distribution inside the loop, you re-seed each time, which can produce repeated numbers or slow down the program. Create them once outside the loop.
  • Using modulo to get a range. rand() % 100 introduces bias because the range may not divide evenly into the generator’s max. The distribution classes handle this correctly.
  • Forgetting to include <random>. You’ll get compile errors about undefined types.

Tips

  • Use std::mt19937 for most tasks. It’s fast and has good quality. For cryptographic security, use std::random_device directly, but note it can be slow or block.
  • Reuse the engine and distribution. Creating them once and reusing them is efficient and maintains good statistical properties.
  • For reproducible results. Seed with a fixed value (e.g., std::mt19937 gen(12345);) when you need to debug or replay a simulation.
  • For floats, use std::uniform_real_distribution. It gives a uniform distribution in [a, b). To include b, use std::nextafter(b, std::numeric_limits<double>::max()) as the upper bound.
  • Use std::shuffle for containers. If you need to randomize a vector, use std::shuffle(vec.begin(), vec.end(), gen); instead of manually picking indices.

Troubleshooting

  • Compilation error: ‘random_device’ is not a member of ‘std’. Your compiler might not support C++11. Add -std=c++11 (or later) to your compile command. For GCC/Clang: g++ -std=c++11 program.cpp.
  • Program always gives the same numbers. Check that you’re seeding with rd() and not a constant. Also, ensure you’re not creating the engine inside a loop.
  • Random numbers are not uniform. This usually happens when you use rand() % range. Switch to the distribution classes.
  • Getting negative numbers unexpectedly. If you use std::uniform_int_distribution with a negative range, that’s fine, but make sure your type is signed. For unsigned types, use unsigned in the template.
  • Program crashes when using std::random_device. On some platforms, random_device may not be available (e.g., MinGW on Windows). A workaround is to use a seed from time(0) or chrono as a fallback, but note that’s less secure.

Frequently Asked Questions

  1. What’s the difference between rand() and <random>? rand() is a simple C function with limited range and quality. <random> provides multiple engines and distributions, giving better randomness and control.
  2. Can I generate a random double between 0 and 1? Yes, use std::uniform_real_distribution<double> dist(0.0, 1.0);. Note that the upper bound is exclusive, so you get numbers in [0, 1).
  3. How do I generate a random boolean? Use std::uniform_int_distribution<int> dist(0, 1); and treat 0 as false, 1 as true. Or use std::bernoulli_distribution.
  4. Is std::random_device secure for passwords? It can be, but it’s not guaranteed. For cryptographic purposes, use a dedicated library like OpenSSL. std::random_device is not standardized to be cryptographically secure.
  5. Why do I get the same sequence when I use std::mt19937 without seeding? The default seed is fixed, so you get the same sequence every time. Always seed with rd() for non-deterministic behavior.
  6. Can I use std::random_device directly to generate numbers? Yes, you can, but it’s not recommended because it may be slow and can block waiting for entropy. Use it only to seed an engine.

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.