Jump to content

[PASCAL] Default value parameters


CouldnoT
 Share

Recommended Posts

Default value parameters

 

We can put default values for procedures and functions in parameters. In this case we can ignore sending these parameters, and the default values will be used.

Look at the next example:

 

program defaultparam;
{$mode objfpc}{$H+}
uses
 {$IFDEF UNIX}{$IFDEF UseCThreads}
 cthreads,
 {$ENDIF}{$ENDIF}
 Classes
 { you can add units after this };
function SumAll(a, b: Integer; c: Integer = 0;
 d: Integer = 0): Integer;
begin
 result:= a + b + c + d;
end;
begin
 Writeln(SumAll(1, 2));
 Writeln(SumAll(1, 2, 3));
 Writeln(SumAll(1, 2, 3, 4));
 Write('Press enter key to close');
 Readln;
end.

 

In this example, we have called the SumAll function three times, the first time using two values, the second time using three values, and the third time using four values. A and B are mandatory parameters and should be sent in all cases because they have no default values. We can ignore sending default parameter values from left to right, for example, if we want to ignore sending a value for c, then we should not send a value for d. Default parameters should start from right to left. We can not declare a default parameter and declare another one that has no default value next to it, like the following example:

 

function ErrorParameters(a: Integer; b: Integer = 10; c: Integer; x: string);

 

We should put the most important parameters on the left, and unimportant ones (that can be ignored) on the right side of the function/procedure's header.

 

 

 

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.