When to srand()?

This is a discussion on When to srand()? within the C++ Programming forums, part of the General Programming Boards category; Hello! Quick Q: If a class needs the random number generator to work right, should I srand() in the constructor? ...

  1. #1
    Evil Member
    Join Date
    Jan 2002
    Posts
    638

    When to srand()?

    Hello!

    Quick Q:

    If a class needs the random number generator to work right, should I srand() in the constructor?

    Will this cause problems in the program is srand() is called elsewhere?

    Or should I just call srand in the main() of any program using that class?

    Is there any convention on this?

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,743
    > Or should I just call srand in the main() of any program using that class
    This is probably the best option

    Typically, you do
    srand(time(NULL));

    But for a short-lived program, time() effectively returns a constant, so if you had
    Code:
    for ( i = 0 ; i < 10 ; i++ ) {
        srand(time(NULL));
        cout << "Rand=" << rand()%100 << endl;
    }
    You'll always end up with the same answers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Use srand() twice in a function?
    By Jake.c in forum C Programming
    Replies: 5
    Last Post: 01-21-2009, 12:51 PM
  2. srand() question
    By Beowolf in forum C++ Programming
    Replies: 10
    Last Post: 11-30-2007, 02:53 PM
  3. srand() in .Net
    By Sad Programmer in forum C++ Programming
    Replies: 6
    Last Post: 07-28-2003, 06:01 PM
  4. Same seed for srand yields different results
    By codegirl in forum C++ Programming
    Replies: 3
    Last Post: 06-23-2003, 03:39 PM
  5. srand()... possible reasons for failure
    By lightatdawn in forum C++ Programming
    Replies: 3
    Last Post: 12-18-2001, 02:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21