title: C++: seeding random number generator outside of main()
body: <p>I was creating a simple program that simulates a coin toss for my class.  (Actually, class is over this term and i'm just working through the rest of the projects that weren't required).  It involves the creating and calling a function that generates a random number between 1 and 2.  Originally, I tried to seed the random number generator within the function that would be using it (coinToss); however, it did not produce a random number.  Each time the program was run it was the same number as though I had only used </p>
  
  <p><code>rand()</code></p>
  
  <p>instead of </p>
  
  <pre><code>unsigned seed = time(0);
  srand(seed);
  rand();
  </code></pre>
  
  <p>Yet, when i moved the above within </p>
  
  <pre><code>int main()
  </code></pre>
  
  <p>it worked fine.</p>
  
  <p>My question is 1)why did it not work when setup within the function that called it and (2) how does <code>rand()</code>
  have access to what was done by <code>srand()</code> if they do not both occur in the same function?
  Obviously, i'm a beginner so please forgive me if i didn't formulate the question correctly.  Also, my book has only briefly touched on <code>rand()</code> and <code>srand()</code> so that's all i really know.<br>
  thanks for any help!</p>
  
  <p>Pertinent code:</p>
  
  <p>First attempt that didn't work:</p>
  
  <pre><code>int main()
  {  
      //...........
      coinToss();
      //...........
   }
  
   int coinToss()
   {
      unsigned seed = time(0);
      srand(seed);
  
      return 1 + rand() % 2;
    }
  </code></pre>
  
  <p>Second attempt which did work:</p>
  
  <pre><code>int main()
  {
      unsigned seed = time(0);
      srand(seed);
  
      coinToss();
   }
  
   int coinToss()
   { 
      return 1 + rand() % 2;
    }
  </code></pre>