Default parameter/pl

From Lazarus wiki
Revision as of 13:17, 30 August 2020 by Slawek (talk | contribs) (Kopia strony en)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Deutsch (de) English (en) español (es) suomi (fi) français (fr) polski (pl) русский (ru)

A default parameter also referred to as optional argument (or default argument) is a function or 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.

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.

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.

Example deadlineDay

{$mode objfpc}

uses SysUtils, DateUtils;

function deadlineDay(day: integer; month: integer = 0): TDateTime;
  n: TDateTime;
  y, m, d: word;
  n := now();
  DecodeDate(n, y, m, d);
  if month = 0 then
    if d > day then
      n := IncMonth(n);
      DecodeDate(n, y, m, d);
    if month < m then
       n := IncYear(n);
    decodeDate(n, y, m, d);
    m := month;
  d := day;
  result := EncodeDate(y, m, d);

Default parameter is used in place of the missing trailing parameter in a call

  • in program call deadlineDay(5) effectively calls deadlineDay(5, 0)
  • in program call deadlineDay(5, 1) does indeed call deadlineDay(5, 1)