What is srand() in c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What is srand() in c++

Srand() vs rand()

30th Dec 2020, 1:06 PM
{H}asintha Ranaweera
{H}asintha Ranaweera - avatar
1 Answer
+ 2
Both srand() and rand(), being a part of the cstdlib library, are used for generating random numbers. Through an internal algorithm, seemingly random numbers are generated if you just use the rand() function, which is used with cout. But when this randomness isn't enough, we can give external arguments through srand() and make it "more random". Srand() doesn't return anything, as it is a void function (that's what I think it is). Giving the same argument again results in the same pattern of random numbers, thus proving the need to change the argument given. So, we use the time(0) function as the argument. Now, the output is "extremely random" as time changes continuously. So, basically speaking, the srand() function is used for receiving an argument for the random-number-generate algorithm.
30th Dec 2020, 1:16 PM
Calvin Thomas
Calvin Thomas - avatar