views:

369

answers:

3

may I know the meaning or even how to read this: srandom( time( NULL ) )?

+3  A: 

The meaning is to initialize the random seed with the current time. time(NULL) returns the current time. srandom() initializes random seed.

Mad Fish
A: 

srandom is a function that initializes the random number generator.

It takes a seed value, which in this code is time(NULL), which is the current time.

This is read, "srandom of time of null".

SLaks
+8  A: 
NULL

A null pointer. Zero. Points to nothing.

time(NULL)

The time function returns the current timestamp as an integer. It accepts an input argument. If the argument is not null, the current time is stored in it.

srandom(time(NULL))

The s means "seed". srandom means "seed the random number generator". It takes an integer as input, reset the PRNG's internal state derived by the input to generate a sequence of random numbers according to it. The seed is sometimes used to ensure 2 sequences of random numbers are the same, to reproduce an equivalent testing condition.

In general, you just put some always changing value there to avoid having the same sequence every time the program is started. The current timestamp is a good value, so time(NULL) is used as the input.

KennyTM
Whether seeding based on time is a good idea depends on the application - though probably only security types would seriously disaprove, and they wouldn't be using standard library random numbers anyway I guess.
Steve314
time() always returns the current time. If the argument is not NULL, the current time will be stored in that pointer too. Since it's always returned anyway, the time(NULL) form is quite common. Good explanation though :)
João da Silva