mardi 23 juin 2020

Understanding srand behavior

I have a program that generate a random key (it just does a rand() % length in a char array filled with a-z, A-Z, 0-9). If I initialize it with srand(time(null)) and I spam execute it, the result is :

key : z1gHYVnRnQnZlIyQy43Vyxouxu27bWXa
key : z1gHYVnRnQnZlIyQy43Vyxouxu27bWXa
key : z1gHYVnRnQnZlIyQy43Vyxouxu27bWXa
key : CdVZTipRSfWI5Mm5174zH9miKAl1Z8aF
key : CdVZTipRSfWI5Mm5174zH9miKAl1Z8aF
key : CdVZTipRSfWI5Mm5174zH9miKAl1Z8aF
key : CdVZTipRSfWI5Mm5174zH9miKAl1Z8aF

which is the expected outcome, the random values are the same within the same second. However, if I give a constant to srand (for example, the posix time of yesterday at noon), I thought I would always get the same key, but not only this isn't the case, they also differ even within the same second. So I'm here to gain a better understanding of this function. Why is this happening ? Isn't time(null) also a constant ?




Aucun commentaire:

Enregistrer un commentaire