I am currently learning C though "C all-in-one Desk Reference for Dummies" and came to the point where it starts teaching how to get random numbers. However, the sample code it gives doesn't work (the compiler comes up with an error "undefined reference to 'random'"). My code is below, copied from the book.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int hat;
hat = random();
printf("%d is a random number.\n",hat);
return(0);
}
DESCRIPTION The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]). The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand().
The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.
C library function - rand() The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
random
and srandom
are non-standard C functions. They are included in glibc on many platforms (linux, BSD etc). However, since they aren't part of the C Standard, they are not required to be available on all compilers.
All standard C compilers however come with rand
and srand
, so just change your program to call rand
instead of random
. If other sample programs in your book call srandom
, then use srand
instead.
Change your program to
#include <stdio.h>
#include <stdlib.h>
int main()
{
int hat;
hat = rand();
printf("%d is a random number.\n",hat);
return(0);
}
The next program in your book probably adds a call to srandom
to make the psuedo random numbers generated to be really random. If so, use srand
instead.
If a beginner book on C actually uses random
and srandom
, then it should probably be thrown out. And any book on C which uses random
and srandom
without telling you that they are non-standard should be thrown out.
The name of the function to create pseudo-random numbers, defined by the ISO C standard, is rand()
.
To actually get a pseudo-random number that looks random, you need to seed the function rand
with srand()
, like the following:
#include <time.h>
#include <stdlib.h>
srand(time(NULL));
int r = rand();
Here, time time()
function (declared in the header time.h
) gets the current calendar time as a value of type time_t
. By doing that, it gets a different value to seed the rand()
function everytime.
EDIT: as pointed by vanza out in comments below, there is a random() function, but it is not defined in the C Standards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With