
Default Parameters
#include <iostream>
using namespace std;
// Print a row with a starting and ending character, with a specified number
// of middle characters between them.
void row(char ends, int num_middle, char middle)
{
cout << ends;
for(int m = num_middle; m--;) cout << middle;
cout << ends << endl;
}
// Draw a box with text.
void box(int width = 9, int height = 5, bool fill = false)
{
// Top row
row('+', width-2, '-');
// Draw internal rows.
for(int m = height-2; m--;)
row('|', width-2, fill ? '#' : ' ');
// Final row.
row('+', width-2, '-');
}
// Box driver.
int main()
{
box();
cout << endl;
box(4);
cout << endl;
box(15, 7);
cout << endl;
box(3,3,true);
}
Default values may be given to parameteters. These are used if the
parameter is not sent. The rules require:
- When a parameter is given a default value, all following
parameters must be given one also.
- When an argument is omitted, all arguments following must be
omitted as well.
- Default values for each parameter must be given once, generally
when first encountered. Generally, they should be given in the
prototype if there is one, but they can then not be given in the
function defintion itself.
So these are illegal:
void joe(int x = 5, double d) { ... }
fred(10, , 20);
Reading: pp. 125-144 exc. arrays