Pointers and references: Difference between revisions

→‎{{header|COBOL}}: Syntax highlighting.
(→‎{{header|jq}}: special case)
imported>Acediast
(→‎{{header|COBOL}}: Syntax highlighting.)
Line 494:
===Pointers===
Pointers are declared like so, optionally with the type or program they will point to:
<syntaxhighlight lang="cobolcobolfree"> 01 ptr USAGE USAGEIS POINTER TO Some-Type.
01 prog-ptr USAGE USAGEIS PROGRAM-POINTER TO "some-program". *> TO is optional</syntaxhighlight>
 
<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>.
<syntaxhighlight lang="cobolcobolfree">ALLOCATE01 heap-item RETURNINGPICTURE IS X, ptrBASED.
 
...
PROCEDURE DIVISION.
FREE ptr</syntaxhighlight>
ALLOCATE heap-item RETURNING ptr
*> ...
FREE ptr</syntaxhighlight>
 
<code>USAGE PROGRAM-POINTER</code> data items are used to point to programs and their entry points.
{{works with|OpenCOBOL}}
{{works with|Visual COBOL}}
<syntaxhighlight lang="cobolcobolfree">SET prog-ptr TO ENTRY "some-program"</syntaxhighlight>
 
Both types of pointer support basic pointer arithmetic.
<syntaxhighlight lang="cobolcobolfree">SET ptr1 UP BY 10
SET ptr2 DOWN BY LENGTH OF foo</syntaxhighlight>
 
Pointers can also be set to point to where other pointers are pointing or to other pointers themselves.
<syntaxhighlight lang="cobolcobolfree">SET ptr1 TO ptr2 *> ptr1 points to where ptr2 points
SET ptr2 TO ADDRESS OF ptr3 *> ptr2 points to ptr3</syntaxhighlight>
 
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.
<syntaxhighlight lang="cobolcobolfree">SET ADDRESS OF foo TO ptr
MOVE "bar" TO foo</syntaxhighlight>
 
===References===
Object references are declared like so, optionally with the class/interface they will reference:
<syntaxhighlight lang="cobolcobolfree"> 01 obj USAGE USAGEIS OBJECT-REFERENCE "some-object".</syntaxhighlight>
 
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.
<syntaxhighlight lang="cobolcobolfree">INVOKE SomeClass "new" RETURNING obj-ref
SET another-obj-ref TO obj-ref</syntaxhighlight>
 
Anonymous user