Pointers and references: Difference between revisions

Added COBOL section.
(Better explanation of the dynamic arrays in D entry)
(Added COBOL section.)
Line 240:
 
{{omit from|Clojure}}
 
=={{header|COBOL}}==
===Pointers===
Pointers are declared like so, optionally with the type or program they will point to:
<lang cobol> 01 ptr USAGE POINTER TO Some-Type.
01 prog-ptr USAGE PROGRAM-POINTER "some-program". *> TO is optional</lang>
 
<code>USAGE POINTER</code> data items are used in conjunction with <code>BASED</code> data items, with <code>ALLOCATE</code> optionally giving a pointer the address of the allocated memory. Pointers can also be used to free allocated memory, which will cause the pointer to be set to <code>NULL</code>.
<lang cobol>ALLOCATE heap-item RETURNING ptr
...
FREE ptr</lang>
 
<code>USAGE PROGRAM-POINTER</code> data items are used to point to programs and their entry points.
{{works with|OpenCOBOL}}
{{works with|Visual COBOL}}
<lang cobol>SET prog-ptr TO ENTRY "some-program"</lang>
 
Both types of pointer support basic pointer arithmetic.
<lang cobol>SET ptr1 UP BY 10
SET ptr2 DOWN BY LENGTH OF foo</lang>
 
Pointers can also be set to point to where other pointers are pointing or to other pointers themselves.
<lang cobol>SET ptr1 TO ptr2 *> ptr1 points to where ptr2 points
SET ptr2 TO ADDRESS OF ptr3 *> ptr2 points to ptr3</lang>
 
To alter the value pointed to by a pointer, the <code>SET</code> statement is needed once again and is used to set the address of <code>BASED</code> or <code>LINKAGE SECTION</code> data items, which can then be used to modify the data.
<lang cobol>SET ADDRESS OF foo TO ptr
MOVE "bar" TO foo</lang>
 
===References===
Object references are declared like so, optionally with the class/interface they will reference:
<lang cobol> 01 obj USAGE OBJECT-REFERENCE "some-object".</lang>
 
They contain either a reference to an object or <code>NULL</code>.
 
They are initialised using by invoking a class constructor, and set using the <code>SET</code> statement.
<lang cobol>INVOKE SomeClass "new" RETURNING obj-ref
SET another-obj-ref TO obj-ref</lang>
 
<code>LINKAGE SECTION</code> data items are essentially references, being passed either the address of an argument (<code>BY REFERENCE</code>), the address of a copy of an argument (<code>BY CONTENT</code>) or the address itself, suitable for using with pointers (<code>BY VALUE</code>).
 
=={{header|Common Lisp}}==
Anonymous user