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

3

5

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!

Icaria answered 16/4, 2014 at 12:43 Comment(3)
Can you include links to the guides?Notochord
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.Rigveda
Is the type of time_t an integer or floating-point?Acrimony
C
4

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?

Caracara answered 16/4, 2014 at 12:51 Comment(2)
+1 for explaining the change in type and good practice to avoid warnings. time_t is often of greater range than unsigned these days.Acrimony
Thanks! took me some time to respond due to holidays.Icaria
J
3

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.

Jujutsu answered 16/4, 2014 at 12:51 Comment(0)
G
0

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.

Goodloe answered 16/4, 2014 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.