Pointers and references: Difference between revisions
Content added Content deleted
(Add Nimrod) |
(Nimrod -> Nim) |
||
Line 650: | Line 650: | ||
END Sum;</lang> |
END Sum;</lang> |
||
=={{header| |
=={{header|Nim}}== |
||
There are two types of pointers in |
There are two types of pointers in Nim. Safe, garbage-collected references and unsafe pointers. |
||
Create a safe reference: |
Create a safe reference: |
||
<lang |
<lang nim>type Foo = ref object |
||
x, y: float |
x, y: float |
||
Line 661: | Line 661: | ||
Accessing the reference: |
Accessing the reference: |
||
<lang |
<lang nim>echo f[]</lang> |
||
When accessing values the dereference operator [] can be left out: |
When accessing values the dereference operator [] can be left out: |
||
<lang |
<lang nim>echo f[].x |
||
f[].y = 12 |
f[].y = 12 |
||
echo f.y |
echo f.y |
||
Line 670: | Line 670: | ||
Create an (unsafe) pointer to an int variable: |
Create an (unsafe) pointer to an int variable: |
||
<lang |
<lang nim>var x = 3 |
||
var p = addr x</lang> |
var p = addr x</lang> |
||
Access the integer variable through the pointer: |
Access the integer variable through the pointer: |
||
<lang |
<lang nim>echo p[] |
||
p[] = 42</lang> |
p[] = 42</lang> |
||
Change the pointer to refer to another object: |
Change the pointer to refer to another object: |
||
<lang |
<lang nim>var y = 12 |
||
p = addr y</lang> |
p = addr y</lang> |
||
Change the pointer to not point to any object: |
Change the pointer to not point to any object: |
||
<lang |
<lang nim>p = nil</lang> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |