I am using rand() for a 6 digit field which needs unique values. Am I doing it right?
What are the odds, rand() can give me similar values on consecutive or frequent calls?
It was unique when I used rand(). But, returned same number when I called srand(time(NULL)) or srand(clock()). Seems, like it’s working opposite for me. Or is it?
As others have pointed out, uniqueness is not guaranteed. However you are probably seeing repeated numbers because you are using srand() and rand() incorrectly.
srand() is used to seed the random number generator. that means a series of calls to rand() after a call to srand will produce a particular series of values. If you call srand() with the same value then rand() will produce the same series of values (for a given implementation, there’s no guarantee between different implementations)
for me this produces:
time() and clock() return the time, but if you call them quickly enough then the value returned will be the same, so you will get the same series of values out of rand().
Additionally rand() is generally not a very good random number generator and using it usually means you have to transform the series of numbers to the distribution you actually need. You should find a different source of randomness and either learn the proper ways to produce the distribution you want or use a library that can do it for you. (for example one common method of producing a ‘random’ number between 0 and N is to do
rand() % Nbut this is not really the best method.C++ provides a much better random number library in
<random>. It provides different PRNG algorithms, such as linear_congruential, mersennne_twister, and possibly even a cryptographically secure RNG (depending on the implementation). It also provides objects for producing a variety of distributions, such as uniform_int_distribution which should avoid the mistake make inrand() % N.