Default
From Free Pascal wiki
Jump to navigationJump to search
Default
is
- a compiler intrinsic
function
returning a zeroed out value, or - a keyword marking a
class
’sarray
property as implicitly accessible.
This article describes the compiler intrinsic. See other articles for the notion in OOP.
zero-idiom
Since FPC 3.0.0 default(dataType)
returns a zero value for the specified dataType
.
program defaults(input, output, stdErr);
var
i: integer;
s: string;
r: tOpaqueData;
begin
i := default(integer); { assigns `0` }
s := default(string); { assigns `nil` or `''` (empty string) }
r := default(tOpaqueData); { assigns `tOpaqueData[]` }
end.
advantages
- The most important “advantage” is that
default
can be used ingeneric
definitions with template parameters.In the context of the definition of theprogram defaultDemo(input, output, stdErr); {$mode objFPC} { --- generic thing -------------------------------------- } type generic thing<storageType> = object data: storageType; constructor init; end; constructor thing.init; begin data := default(storageType); end; { === MAIN =============================================== } type arr = array[1..10] of integer; var x: specialize thing<tBoundArray>; y: specialize thing<arr>; begin end.
generic
data typething
it is not yet known whatstorageType
will be. Therefore, we could not possibly write a literal value such as0
ornil
. However, we can usedefault
to overcome this hurdle. Upon specialization the correct zero value will be inserted. - Furthermore, the compiler can choose a faster implementation than, for instance, a respective
fillChar(myVariable, sizeOf(myVariable), chr(0))
.
caveats
- Despite its name,
default
is really just a synonym for zero. It can be used to assign values out of range:See FPC issue 34972.program faultyDefault(input, output, stdErr); {$rangeChecks on} type typeWithoutZeroValue = -1337..-42; var i: typeWithoutZeroValue; begin i := -1024; { ✔ OK } {i := 0; ✘ not OK } i := default(typeWithoutZeroValue); { OK again } writeLn(i); end.
Default
cannot be applied onfile
ortext
data types and structured data types containing such.