Pointers and references: Difference between revisions

Content added Content deleted
Line 58: Line 58:
</ada>
</ada>
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
The following code creates a pointer to an INT variable
The following code creates a pointer to an INT variable:
INT var := 3;
INT var := 3;
REF INT pointer := var;
REF INT pointer := var;
Line 64: Line 64:
INT v = pointer; # sets v to the value of var (i.e. 3) #
INT v = pointer; # sets v to the value of var (i.e. 3) #
REF INT(pointer) := 42; # sets var to 42 #
REF INT(pointer) := 42; # sets var to 42 #
Change the pointer to refer to another object
Change the pointer to refer to another object:
INT othervar;
INT othervar;
pointer := othervar;
pointer := othervar;
Change the pointer to not point to any object
Change the pointer to not point to any object:
pointer := NIL; # 0 cannot be cast to NIL #
pointer := NIL; # 0 cannot be cast to NIL #
Get a pointer to the first element of an array:
Get a pointer to the first element of an array:
Line 78: Line 78:
The following code create a constant reference to an INT variable:
The following code create a constant reference to an INT variable:
REF INT alias = var;
REF INT alias = var;
Access the integer variable through the reference
Access the integer variable through the reference:
INT v2 = alias; # sets v2 to the value of var, that is, 3 #
INT v2 = alias; # sets v2 to the value of var, that is, 3 #
alias := 42; # sets var to 42 #
alias := 42; # sets var to 42 #
References cannot be changed to refer to other objects, and cannot (legally) made to refer to no object.
References cannot be changed to refer to other objects, and cannot (legally) made to refer to no object.


pointers can be compared, but only for equality
Pointers can be compared, but only for equality:
printf(($"alias "b("IS","ISNT")" var!"l$, alias IS var));
printf(($"alias "b("IS","ISNT")" var!"l$, alias IS var));
Output: alias IS var!
Output: alias IS var!
Line 92: Line 92:
Changing the reference to refer to another object of the array is not possible.
Changing the reference to refer to another object of the array is not possible.


ALGOL 68 also allows pointers to slices of rows and/or columns of arrays
ALGOL 68 also allows pointers to slices of rows and/or columns of arrays:
[9,9]INT sudoku;
[9,9]INT sudoku;
REF [,]INT middle;
REF [,]INT middle;
middle := sudoku[3:5,3:5];
middle := sudoku[3:5,3:5];


# This includes pointers to slices character arrays #
This includes pointers to slices character arrays:
[30]CHAR hay stack := "straw straw needle straw straw";
[30]CHAR hay stack := "straw straw needle straw straw";
REF[]CHAR needle = hay stack[13:18];
REF[]CHAR needle = hay stack[13:18];