4
votes

I've seen some guide on generating random numbers with C: two things got me wondering:

  1. it is said that in addition to stdlib.h and time.h libraries I have to include the math.h library for it to work, why? (afaik the srand and rand functions are in stdlib)?
  2. in the example the srand function is written the following way:

    srand((unsingned int)time(NULL);
    

I'm using codeblocks and it works properly without the unsigned int and the math library, so why do they include it in the example?

thanks!

3
Can you include links to the guides?Shafik Yaghmour
Have you tried it? What error does the compiler return, if any, if you omit math.h? It might give you some clues. Also, take a look at the type that time() returns, and what srand() expects.lorenzog
Is the type of time_t an integer or floating-point?chux - Reinstate Monica

3 Answers

4
votes

The function time returns a time_t value, while srand expect an unsigned int argument. Without the cast, the compiler may produce a warning and depending on the compiler flags this may cause the compilation to fail. In general it is good practice to avoid warnings.

Nothing in the line you show requires the inclusion of math.h. Probably this comment refers to some other part of the code?

3
votes

Do I need '(unsigned int)' before 'time(null)' in the srand function in c?

time() returns a variable of the type time_t. What type size this corresponds to on your compiler is implementation-defined. You have to check the compiler documentation.

it is said that in addition to stdlib.h and time.h libraries I have to include the math.h library for it to work, why?

For the line posted, math.h is not needed. Most likely it was needed for some other part of the code.

0
votes

You don't need to include the math library.

The example works most of the time, but is technically incorrect, because casting to an incompatible type is invalid.

The only correct way is to hash the bytes of the variable time_t.

time_t t = time( NULL ) ;
char* p = ( char* )&t ; 
unsigned int hash = 0 ;

for( int i = 0 ; i < sizeof( time_t ) ; i++ )  
    hash += p[i] ;

And then use hash in your srand() function.

You are allowed to cast to char* and then use the pointer. The hash function is very simple, you might want to choose a better one.