I'm currently developing a game (And no, just because that's the case doesn't mean this belongs in game development), and I've run into a problem.

Basically, I need to generate a random number.
The number needs to stay the same after it is generated once.
The code is in an infinite loop, which makes it very difficult.

I've tried getting around it by making it choose the number at the top where all the other global variables are declared, but this makes the variable choose a value before srand is even activated, so it just picks the same number each time.


6 Years
Discussion Span
Last Post by Oinkertop

umm something like so:

struct ConstantRandom{
  int randNum;
  bool isFirstTime;
 ConstantRandom(): isFirstTime(true), randNum(0){};
 int operator()(){
   if(isFirstTime){ randNum = rand();  isFirstTime = false;}
   return randNum;
int main(){
 srand( time(0) );
 ConstantRandom cr;
 int i = cr(); //i equals some random number
 int j = cr(); // j should equal to i

Basically your just saving a state

Edited by firstPerson: n/a


I had to play around with it a bit, but it worked.
Thank you very much.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.