Pointers and references: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
(→Pascal: expand) |
||
Line 1,375: | Line 1,375: | ||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
See [[ |
''See also [[#Delphi|Delphi]]'' |
||
Pascal does not support pointer operations on the stack. |
|||
In fact, Pascal does not even “know” there is a stack. |
|||
<lang pascal>program pointerDemo; |
|||
type |
|||
{ |
|||
A new pointer data type is declared by `↑` followed by a data type name, |
|||
the domain. |
|||
The domain data type may not have been declared yet, but must be |
|||
declared within the current `type` section. |
|||
Most compilers do not support the reference token `↑` as specified in |
|||
the ISO standards 7185 and 10206, but use the alternative `^` (caret). |
|||
} |
|||
integerReference = ^integer; |
|||
var |
|||
integerLocation: integerReference; |
|||
begin |
|||
{ |
|||
The procedure `new` taken one pointer variable and allocates memory for |
|||
one new instance of the pointer domain’s data type (here an `integer`). |
|||
The pointer variable will hold the address of the allocated instance. |
|||
} |
|||
new(integerLocation); |
|||
{ |
|||
Dereferencing a pointer is done via appending `↑` to the variable’s |
|||
name. All operations on the domain type are now possible. |
|||
} |
|||
integerLocation^ := 42; |
|||
{ |
|||
The procedure `dispose` takes one pointer variable and releases the |
|||
underlying memory. The supplied variable is otherwise not modified. |
|||
} |
|||
dispose(integerLocation); |
|||
{ |
|||
In Pascal, `dispose` is not necessary. Any excess memory is automatically |
|||
released after `program` termination. |
|||
} |
|||
end.</lang> |
|||
Furthermore, <tt>new</tt> and <tt>dispose</tt> accept further parameters if the pointer variable’s domain type is a variant <tt>record</tt> (or, in Extended Pascal, a schema). |
|||
This permits the processor to allocate memory merely for the specified variant (or, in Extended Pascal, a discriminant), but also forbids you to change the variant (of a <tt>record</tt>). |
|||
It is imperative the selectors in <tt>dispose</tt> match to the corresponding <tt>new</tt>. |
|||
<lang pascal>program variantRecordDemo; |
|||
type |
|||
fooReference = ^foo; |
|||
foo = record |
|||
case Boolean of |
|||
false: ( ); |
|||
true: (location: fooReference); |
|||
end; |
|||
var |
|||
head: fooReference; |
|||
begin |
|||
new(head, true); |
|||
{ … } |
|||
dispose(head, true); |
|||
end.</lang> |
|||
As a special case of pointers, functions and procedures can be passed as parameters to routines. |
|||
<lang pascal>program routineParameterDemo(output); |
|||
procedure foo(function f: Boolean); |
|||
begin |
|||
writeLn(f); |
|||
end; |
|||
function bar: Boolean; |
|||
begin |
|||
bar := false |
|||
end; |
|||
begin |
|||
foo(bar); |
|||
end.</lang> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |