Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

random

srand

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!

like image 691
Medvednic Avatar asked Apr 16 '14 12:04

Medvednic


2 Answers

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?

like image 55
Ivaylo Strandjev Avatar answered Sep 22 '22 14:09

Ivaylo Strandjev


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.

like image 20
Lundin Avatar answered Sep 24 '22 14:09

Lundin