< Previous | Contents | Next >

Assigning Default Arguments to

Parameters

The askNumber() function asks the user for a number between an upper and a lower limit. The function keeps asking until the user enters a number within the range, and then it returns the number. I first call the function in main() with:

int number = askNumber(5);

As a result of this code, the parameter high in askNumber() is assigned 5. Because I dont provide any value for the second parameter, low, it gets assigned the default value of 1. This means the function prompts the user for a number between 1 and 5.


Tra p

image

When you are calling a function with default arguments, once you omit an argument, you must omit arguments for all remaining parameters. For example, given the prototype

void setDisplay(int height, int width, int depth = 32, bool fullScreen = true);

174 Chapter 5 n Functions: Mad Lib


a valid call to the function would be

setDisplay(1680, 1050);

while an illegal call would be

setDisplay(1680, 1050, false);

image


Once the user enters a valid number, askNumber() returns that value and ends. Back in main(), the value is assigned to number and displayed.