srand in D

Paul Backus snarwin at gmail.com
Sun Oct 31 17:17:12 UTC 2021


On Sunday, 31 October 2021 at 16:54:35 UTC, pascal111 wrote:
> Hi! I'm C learner and found the high similarity between C and 
> D, and was converting C code into D but couldn't get the 
> equivalent of this C statement "srand(time(NULL));".

Since D gives you access to the C standard library, you can use 
pretty much exactly the same code in D:

```d
import core.stdc.stdlib; // bindings for <stdlib.h>
import core.stdc.time; // bindings for <time.h>

srand(time(null)); // null is lower-case in D
```

If you want to use D's standard library, you can instead use 
[`std.random.rndGen`][1], the default random number generator. 
Its documentation says:

> It is allocated per-thread and initialized to an unpredictable 
> value for each thread.

In other words, it is seeded for you automatically. So when you 
are converting C code that uses `rand` to D code that uses 
`rndGen`, you can simply delete the line `srand(time(NULL));`, 
and it will work ask expected.

If you wanted to seed it yourself, however, you would do it using 
the `.seed` method, and generate the seed using 
[`std.random.unpredictableSeed`][2].

```d
import std.random;

rndGen.seed(unpredictableSeed());
```

This is mainly useful when you are using a custom RNG instead of 
the default `rndGen`, since custom RNGs are *not* automatically 
seeded.

[1]: https://phobos.dpldocs.info/std.random.rndGen.html
[2]: 
https://phobos.dpldocs.info/std.random.unpredictableSeed.1.html


More information about the Digitalmars-d-learn mailing list