Question

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!

Was it helpful?

Solution

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?

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top