Default Arguments
Default arguments is a shortcut that is not available in C. It allows function arguments to automatically be provided in the function call. Default arguments are commonly used when a function is called repeatedly using the same argument value(s)
Here's an example of a function, power(), that has a default argument.
Example 2-4
1 // File: ex2-4.cpp
2
3 #include <iostream>
4 using namespace std;
5
6 long power(int,int = 2); // function prototype with default argument
7
8 int main(void)
9 {
10 cout << power(5) << endl; // use default argument
11 cout << power(2,10) << endl; // don’t use default argument
12 cout << power(12345) << endl; // use default argument
13
14 return 0;
15 }
16
17
18 long power(int x, int y)
19 {
20 long num = 1;
21 for (int i = 1; i <= y; i++) num *= x;
22 return num;
23 }***** Sample Output *****
25
1024
152399025
A function may possess several default arguments. Such as ...
void funk1 (int, double, int = 5, double = 3.14);
or
int funk2 (int = 1, int = 2, int = 3, int = 4);
Call's to funk1 could look like:
funk1(2,3.14,6,1.23) // all arguments are supplied
or
funk1(2,3.14,6) // the same as funk1(2,3.14,6,3.14)
or
funk1(2,3.14) // the same as funk1(2,3.14,5,3.14)
Calls to funk2 could look like:
funk2(2,4,6,8) // all arguments are supplied
or
funk2(2,4,6) // the same as funk2(2,4,6,4)
or
funk2(2,4) // the same as funk2(2,4,3,4)
or
funk2(2) // the same as funk2(2,2,3,4)
or
funk2() // all arguments are default
Notes
- In a function argument list, mandatory arguments may never follow default arguments. For example, funk(int,int,int=2,int=5) is OK, but funk(int,int=3,int,int=6) is not OK. Default arguments must come at the end of the argument list.
- Default arguments should be placed in the function prototype, not the function heading. This (strong) recommendation should be followed, even if your compiler permits the default argument in the function heading. The exception to this is the situation where the function is defined before it is called and, in this case, the prototype is not necessary.
- Default arguments may not be repeated in both the function prototype and the heading of the function definition.
Default arguments 一定要在 argument list 的最後.
建議將 default arguments 放在 function prototype 下; 而不要再 function heading 下.
沒有留言:
張貼留言