Pointers and references: Difference between revisions

Line 57:
end loop;
</ada>
=={{header|ALGOL 68}}==
The following code creates a pointer to an INT variable
INT var := 3;
REF INT pointer := var;
Access the integer variable through the pointer:
INT v = pointer; # sets v to the value of var (i.e. 3) #
REF INT(pointer) := 42; # sets var to 42 #
Change the pointer to refer to another object
INT othervar;
pointer := othervar;
Change the pointer to not point to any object
pointer := NIL; # 0 cannot be cast to NIL #
Get a pointer to the first element of an array:
[9]INT array;
pointer := array[LWB array];
There is no pointer arithmetic, eg no p +:=3
 
'''With references:'''
 
The following code create a constant reference to an INT variable:
REF INT alias = var;
Access the integer variable through the reference
INT v2 = alias; # sets v2 to the value of var, that is, 3 #
alias := 42; # sets var to 42 #
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
printf(($"alias "b("IS","ISNT")" var!"l$, alias IS var));
Output: alias IS var!
 
Get a reference to the first element of an array:
[9]INT array2;
REF INT ref3 = array2[LWB array2];
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
[9,9]INT sudoku;
REF [,]INT middle;
middle := sudoku[3:5,3:5];
 
# This includes pointers to slices character arrays #
[30]CHAR hay stack := "straw straw needle straw straw";
REF[]CHAR needle = hay stack[13:18];
needle[2:3] := "oo";
print((hay stack))
Output: straw straw noodle straw straw
 
=={{header|C}} and {{header|C++}}==
The following code creates a pointer to an int variable