Search code examples
cposix

Why do we use 'NULL'?


Why do we use 'NULL' in code below.

Why can't we multiply the seed by an integer?

Sorry I am new to C++.

CODE

srand(time(NULL));

Solution

  • The time function can write the time to a location provided by a pointer to the function call. This pointer argument can be a null pointer, and then time only returns the current time.

    On most systems the time function returns the number of seconds since an epoch, and as such is a pretty unique integer value to use for seeding the random number generator.


    The single statement

    srand(time(NULL));
    

    is equivalent to

    time_t temp_time = time(NULL);
    srand(temp_time);
    

    Or if we want to use a non-null pointer

    time_t temp_time;
    time(&temp_time);
    srand(temp_time);