Is there a function or will I have to use a third party library?
STL doesn't exist for C. You have to call rand
, or better yet, random
. These are declared in the standard library header stdlib.h
. rand
is POSIX, random
is a BSD spec function.
The difference is that random
returns a much more usable 32-bit random number, and rand
typically returns a 16-bit number. The BSD manpages show that the lower bits of rand
are cyclic and predictable, so rand
is potentially useless for small numbers.
Well, STL is C++, not C, so I don't know what you want. If you want C, however, there is the rand()
and srand()
functions:
int rand(void);
void srand(unsigned seed);
These are both part of ANSI C. There is also the random()
function:
long random(void);
But as far as I can tell, random()
is not standard ANSI C. A third-party library may not be a bad idea, but it all depends on how random of a number you really need to generate.
You want to use rand()
. Note (VERY IMPORTANT): make sure to set the seed for the rand function. If you do not, your random numbers are not truly (pseudo)random. This is very, very, very important. Thankfully, you can usually use some combination of the system ticks timer and the date to get a good seed.
The rand()
function in <stdlib.h>
returns a pseudo-random integer between 0 and RAND_MAX
. You can use srand(unsigned int seed)
to set a seed. It's common practice to use the %
in conjunction with rand()
to get a different range (though bear in mind that this throws off the uniformity somewhat). eg:
/* random int between 0 and 19 */
int r = rand() % 20;
Is there a FAQ entry for this question? It seems to be a Question that gets Asked very Frequently. I see a couple just from the past few hours.
FWIW, the answer is that yes, there is a stdlib call "rand"; this function is tuned primarily for speed and distribution, not for unpredictability. Almost all built-in random functions for various languages and frameworks use this function by default. There are also "cryptographic" random number generators that are much less predictable, but run much slower. These should be used in any sort of security-related application.
#include <time.h>
#include <stdlib.h>
srand(time(NULL));
int r = rand();
If you need better quality pseudo random numbers than what stdlib
provides, check out Mersenne Twister. It's faster, too. Sample implementations are plentiful, for example here.