default parameters
Pass parameters to function
// passing in parameters to reuse function with different values
void fun2Demo(int low, int high) {
cout << "fun2Demo with ( " << low << " , " << high << " )" << endl;
for (int i= high; i > low; i--) {
cout << i << " ";
}
cout << endl;
}
Default parameters
// default function parameters such that it can be called with 2 or 1 or 0 parameters
void fun3Demo(int low=LO, int high=HI) {
cout << "fun3Demo with ( " << low << " , " << high << " )" << endl;
for (int i= low; i < high; i++) {
if (i==5) continue;
if (i==8) break;
if (i%3==0) cout << "aa"; else cout << i;
cout << endl;
}
cout << endl;
}
void funDemo() {
fun2Demo(1,12);
fun3Demo();
fun3Demo(3);
fun3Demo(7, 11);
}
Note that all 3 func3Demo calls are legal. It is a very useful feature when a function anticipates variable number of inputs. An example is in the resistors calculation quiz.
Furthermore, you can have some parameters have default and others do not. However, parameters with defaults MUST appears AFTER every non-default parameter. (wonder why?) In our example, it is legal to define it as fun4Demo(int low, int high=HI);
things to know
the advantage of passing parameters to function versus code it in #define as shown here.
the ability of using default parameters to enhance the flexibility of a function
use "continue" and "break" statements to control the flow of a loop.