srand() + rand() with local scope

Solution for srand() + rand() with local scope
is Given Below:

I have a function that calls srand and rand like this:

void foo() {
   int seed = some_operation();
   int value = std::rand();
   // Do something with random value

However, I don’t want to change the global state of rand. Whats the easiest way to get a random number then?


  • random number must be deterministic based on seed
  • C++11 is fine
  • foo should be thread safe
  • the global state of rand should not be modified


There is a stackoverflow question asking how to generate random numbers. The accepted answer however shows how to generate truly unique random numbers, using a slow std::random_device. I just needed a simple generator using a fixed seed instead.

C++11 is fine

Then use the new pseudorandom number library:

#include <random>

int foo() {
    int seed = some_operation();
    std::minstd_rand rand(seed);
    int value = rand();
    // Do something with random value

minstd_rand is a simple linear congruential engine, similar to that typically used by std::rand(), but with its state encapsulated in a class. Other engines are available, if you need a higher quality pseudorandom sequence. The Mersenne Twister, std::mt19937, is usually a good choice if you don’t have specific requirements.

<random> defines a number of PRNG classes that you can use, which do not use global states.

For example, using a default Mersenne Twister, std::mt19937:

#include <iostream>
#include <random>

int main() {
  int seed = 1234;
  std::mt19937 rng(seed);
  std::cout << "Random number: " << rng() << std::endl;

One approach is to provide your own implementation, with its own seed data. A template for doing that is provided in the manpage for rand().

static unsigned long next = 1;

/* RAND_MAX assumed to be 32767 */
int myrand(void) {
    next = next * 1103515245 + 12345;
    return((unsigned)(next/65536) % 32768);

void mysrand(unsigned seed) {
    next = seed;