Default parameter: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Default parameter
| Old | New | Line | |
|---|---|---|---|
| 1 | + | A default parameter also referred to as optional argument (or default argument) is a [[Function|function]] or [[Procedure|procedure]] parameter that has a default value provided to it. If the programmer does not supply a value for this parameter, the default value will be used. If the programmer does supply a value for the default parameter, the programmer-supplied value is used. | |
| 2 | + | ||
| 3 | + | The programmer can extend an existing function or procedure by adding some parameters that have default value instead of writing an identical method with different parameters. | |
| 4 | + | ||
| 5 | + | Beware: Once in a parameter list an optional parameter is defined, all following parameters have to be optional, too. A mandatory parameter must not have a later position than an optional parameter. | |
| 6 | + | ||
| 7 | + | ## Example `deadlineDay` | |
| 8 | + | ||
| 9 | + | ``` pascal | |
| 10 | + | {$mode objfpc} | |
| 11 | + | ||
| 12 | + | uses SysUtils, DateUtils; | |
| 13 | + | ||
| 14 | + | function deadlineDay(day: integer; month: integer = 0): TDateTime; | |
| 15 | + | var | |
| 16 | + | n: TDateTime; | |
| 17 | + | y, m, d: word; | |
| 18 | + | begin | |
| 19 | + | n := now(); | |
| 20 | + | DecodeDate(n, y, m, d); | |
| 21 | + | if month = 0 then | |
| 22 | + | begin | |
| 23 | + | if d > day then | |
| 24 | + | begin | |
| 25 | + | n := IncMonth(n); | |
| 26 | + | DecodeDate(n, y, m, d); | |
| 27 | + | end; | |
| 28 | + | end | |
| 29 | + | else | |
| 30 | + | begin | |
| 31 | + | if month < m then | |
| 32 | + | begin | |
| 33 | + | n := IncYear(n); | |
| 34 | + | end; | |
| 35 | + | decodeDate(n, y, m, d); | |
| 36 | + | m := month; | |
| 37 | + | end; | |
| 38 | + | d := day; | |
| 39 | + | result := EncodeDate(y, m, d); | |
| 40 | + | end; | |
| 41 | + | ``` | |
| 42 | + | ||
| 43 | + | Default parameter is used in place of the missing trailing parameter in a call | |
| 44 | + | ||
| 45 | + | - in program call `deadlineDay(5)` effectively calls `deadlineDay(5, 0)` | |
| 46 | + | - in program call `deadlineDay(5, 1)` does indeed call `deadlineDay(5, 1)` | |
| 47 | + | ||
| 48 | + | --- | |
| 49 | + | *From the Free Pascal wiki, page "Default parameter", as it stood on 2020-02-12 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
