What's the Right Way to Use the Rand() Function in C++

What's the Right Way to use the rand() Function in C++?

Option 2 isn't difficult, here you go:

srand(time(NULL));

you'll need to include stdlib.h for srand() and time.h for time().

How does rand() work in C?

You should know that the easiest way to get information about the C standard library is by using manual pages on a Linux/UNIX system.

Manual chapter 3 is where you'll find manual pages regarding the standard library. To get documentation for rand, type man 3 rand at a shell prompt.

In case you don't have the manual pages handy, I'll just quote from the description here:

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(). These sequences
are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically
seeded with a value of 1.

The function rand() is not reentrant or thread-safe, since it uses hid‐
den state that is modified on each call. This might just be the seed
value to be used by the next call, or it might be something more elabo‐
rate. In order to get reproducible behavior in a threaded application,
this state must be made explicit; this can be done using the reentrant
function rand_r().

Like rand(), rand_r() returns a pseudo-random integer in the range
[0, RAND_MAX]. The seedp argument is a pointer to an unsigned int that
is used to store state between calls. If rand_r() is called with the
same initial value for the integer pointed to by seedp, and that value
is not modified between calls, then the same pseudo-random sequence
will result.

The value pointed to by the seedp argument of rand_r() provides only a
very small amount of state, so this function will be a weak pseudo-ran‐
dom generator. Try drand48_r(3) instead.

RETURN VALUE

The rand() and rand_r() functions return a value between 0 and RAND_MAX
(inclusive). The srand() function returns no value.

If you want to know how the code itself works, I can break it down for you:

#include <stdio.h>

Includes the standard I/O libraries. (needed in this case to get the definition of printf().)

#include <stdlib.h>

Includes the C standard library (for the current platform). This will be needed to get the definition of rand(), srand(), and time().

int main()

Defines the function main(), which will be sought out as the entry point for your compiled executable file at a later date.

{

Defines the scope of main().

   int i, n;

Allocates memory space on the stack for two int variables, i, and n.

   time_t t;

Allocates memory space on the stack for a time_t structure, which will be used later for the current time.

   n = 5;

Initializes int n to the value 5.

   /* Intializes random number generator */
srand((unsigned) time(&t));

First calls time() with the argument being the memory address of the time_t allocated on the stack earlier. This will populate the time_t with the current time. (which is actually just expressed as an integer - the number of seconds since the "epoch" - see man 2 time)

Next, calls srand() with that value (after casting it to unsigned int, which presumably avoids a compiler warning, but is probably safe if you know that sizeof(time_t) >= sizeof(int).). Calling srand() here will seed the PRNG (pseudo-random number generator).

   /* Print 5 random numbers from 0 to 49 */
for( i = 0 ; i < n ; i++ )
{

In the for statement (in my own words), you'll see <initialization-instruction> ; <condition> ; <loop-instruction>. The contents of the loop are executed while <condition> is true (which, in C terms, means non-zero, but that's a separate discussion).

Set the int i defined earlier to zero. While i is less than n, do the operations within the curly braces ({ ... }), then increment i (++i) and check the condition again. (n was defined to be 5 earlier, so loop though the values [0, 1, 2, 3, 4])

      printf("%d\n", rand() % 50);

The printf() call uses format strings to print its output. The %d means you want printf to print out the first parameter assuming that it is an unsigned decimal integer. If you include more format strings in the printf call, you should include multiple corresponding parameters to the printf() function.

The \n, when it appears in a character or string constant, is a linefeed. So after the number is printed, the cursor will move to the beginning of the next line.

Finally, rand() % 50 means "call rand(), divide the result by 50, and then take the remainder". (The % is the modulus operator, which means you want the remainder.) For example, if rand() returns 1000, you'll get 0 printed to the screen, since 1000 % 50 == 0 (that is, 1000 divided by 50 equals 20, remainder 0).

So the end result will be printing a pseudo-random value between 0 and 49.

   }

return(0);

This will cause main() to finish executing and return to its caller (probably whatever code loads binaries on your operating system). It will also most likely cause the exit status of your program to be 0.

}

How to generate a random int in C?

Note: Don't use rand() for security. If you need a cryptographically secure number, see this answer instead.

#include <time.h>
#include <stdlib.h>

srand(time(NULL)); // Initialization, should only be called once.
int r = rand(); // Returns a pseudo-random integer between 0 and RAND_MAX.

On Linux, you might prefer to use random and srandom.

using rand() in a function in c

srand() initializes the PRNG (pseudo random number generator) of your standard C library. A PRNG works by applying more-or-less complicated arithmetic operations to a value stored internally and returning part of the result as the next "random" number. srand() sets this internal state.

If you call srand() every time in your function, you won't get (sensible) random numbers because the internal state is reset every time. Call it once your program starts.

Proper use of rand()?

When you call rand(), it gives you a number between 0 and RAND_MAX. When you use something like rand() % 8, it gives you a random number between 0 and 7. This is more range than you want the random numbers to span. You only want the random numbers to be from 0 through 2 (0, 1, or 2), then add the offset for the first row.

For example, (rand() % 8) + 6 gives you a random number from 0+6=6 through 7+6=13. Instead, use (rand() % 3) + 6 to give you 0+6=6 through 2+6=8.



Related Topics



Leave a reply



Submit