srand() — why call it only once?

2018-12-31 00:02发布

This question is about a comment in this question Recommended way to initialize srand? The first comment says that srand() should be called only ONCE in an application. Why is it so?

标签: c random srand
7条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 00:28

The reason is that srand() sets the initial state of the random generator, and all the values that generator produces are only "random enough" if you don't touch the state yourself in between.

For example you could do:

int getRandomValue()
{
    srand(time(0));
    return rand();
}

and then if you call that function repeatedly so that time() returns the same values in adjacent calls you just get the same value generated - that's by design.

查看更多
登录 后发表回答