Search code examples
crandomcastingsrand

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


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!


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?