The reserved word
nil represents the special value of a pointer variable not pointing anywhere particular.
In FPC it is implemented as
pointer(0) (the numeric value
0), however the programmer is not supposed to use this fact.
In other programming languages, e.g in C, someone writes
The terms “null pointer” or “nil pointer” are used interchangeably, even among Pascal programmers.
There are two popular explanations of
One says, nil is short for the Latin word “nihil” meaning “nothing”.
The other suggests,
NIL is an English acronym standing for “not in list.”
Maybe, since the German word „Null“ stands for the digit “zero”, and in order to avoid confusion, or to distinguish between the concept and value, the word
nil was chosen.
At any rate, this does not have any implications while programming.
1program nilDemo(input, output, stderr); 2var 3 loc: pointer; 4 chk: array of boolean; 5 msg: PChar; 6 obj: TObject; 7begin 8 loc := nil; 9 // clears dynamic array 10 chk := nil; 11 // empty string 12 msg := nil; 13 // loses reference to object 14 obj := nil; 15end.
nil to a dynamic array is equivalent to the statement
The values of the array are lost.
However, there is no comparable mechanism for other types, e.g. assigning
nil to a
pointer variable will not release (de-allocate) the memory that is possibly been occupied by the referenced structure.
In a Pascal's manner you usually do not write expressions like
pointerVariable = nil but use more explanatory identifiers.
system.assigned will be replaced by the exact same expression, but conceals the fact a variable is (implemented as) a pointer.
So its usage is optional.
sysUtils.freeAndNil will call a class's
free routine and assign
nil to the handed pointer (variable of type
Although it is a good idea, to clear pointers which do not point to valid objects anymore, this can make debugging more difficult, since there is no pointer available, pointing to the address a certain object used to be.