Thread: C++ ctime library. How is the functions srand(time(0)) and rand() defined?

  1. #1
    Registered User
    Join Date
    Feb 2013
    Location
    Sweden
    Posts
    171

    Question C++ ctime library. How is the functions srand(time(0)) and rand() defined?

    I don't know if it's the right place to post this kind of question here, so sorry if so.

    But I've been wondering about the srand(), time() and rand() functions since they all make sense when generating a random number. I know that rand() counts how many seconds that have past since 1 Januari 1970 but I don't get how they define the function and the variable that have to increase itself every second.

    How does this help us with generating random numbers, I see that it works, but I wanna know more deeply about how they've figured this out and how they got it to work until we hit year 2038. But they've solved that too with something like time_t which goes 584 billon years further into the future until it reaches its limit.
    If I've heard right.

    So how did they create these functions from the beginning is my question?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I think your question is really about time(), not rand() (and it looks like you confused rand() and time()). The use of time() with srand() is merely to seed the PRNG such that the seed is unlikely to be repeated when running the program several times (unless you run it so quickly after the previous run that the time value returned has not changed).

    Anyway, the implementation of time() likely involves a system call or something along those lines that at some point accesses the computer's clock.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 07-17-2014, 07:11 AM
  2. Using rand() and srand() functions
    By Aeria Gloris in forum C Programming
    Replies: 9
    Last Post: 11-05-2009, 11:29 AM
  3. Replies: 3
    Last Post: 05-12-2009, 06:17 AM
  4. srand() and rand()
    By Mr.Sellars in forum C++ Programming
    Replies: 3
    Last Post: 08-12-2007, 03:19 PM
  5. srand() or rand()???
    By bajanstar in forum C Programming
    Replies: 4
    Last Post: 03-04-2005, 12:58 PM