< Previous | Contents | Next >

Calling the rand() Function

One of the first things I do in the program is include a new file:

#include <cstdlib>

The file cstdlib contains (among other things) functions that deal with generating random numbers. Because Ive included the file, Im free to call

70 Chapter 2 n Truth, Branching, and the Game Loop: Guess My Number


the functions it contains, including the function rand(), which is exactly what I do in main():

int randomNumber = rand(); //generate random number


As you learned in Chapter 1, functions are pieces of code that can do some work and return a value. You call or invoke a function by using its name followed by a pair of parentheses. If a function returns a value, you can assign that value to a variable. Thats what I do here with my use of the assignment statement. I assign the value returned by rand() (a random number) to randomNumber.


Hi n t

image

The rand() function generates a random number between 0 and at least 32767. The exact upper limit depends on your implementation of C++. The upper limit is stored in the constant RAND_MAX, which is defined in cstdlib. So if you want to know the maximum random number rand() can generate, just send RAND_MAX to cout.

image


Functions can also take values to use in their work. You provide these values by placing them between the parentheses after the function name, separated by commas. These values are called arguments, and when you provide them, you pass them to the function. I didnt pass any values to rand() because the function doesnt take any arguments.