Variable declaration reset: Difference between revisions
Content added Content deleted
m (Python example) |
(julia example) |
||
Line 294: | Line 294: | ||
2 |
2 |
||
5 |
5 |
||
</pre> |
|||
=={{header|Julia}}== |
|||
In Julia, variables are declared by being defined. Because variables also must be initialized before they are |
|||
referred to in compiled code, the code below yields an error that the variable `prev` is not defined: |
|||
<lang julia> |
|||
s = [1, 2, 2, 3, 4, 4, 5] |
|||
for i in eachindex(s) |
|||
curr = s[i] |
|||
i > 1 && curr == prev && println(i) |
|||
prev = curr |
|||
end |
|||
</lang> |
|||
If the variable `prev` is defined before the `for` statement, the code then runs. We also may |
|||
declare the variable `prev` as global to refer explicitly to the variable declared outside of the for block: |
|||
<lang julia> |
|||
s = [1, 2, 2, 3, 4, 4, 5] |
|||
prev = -1 |
|||
for i in eachindex(s) |
|||
global prev |
|||
curr = s[i] |
|||
i > 1 && curr == prev && println(i) |
|||
prev = curr |
|||
end |
|||
</lang> {{out}} |
|||
<pre> |
|||
3 |
|||
6 |
|||
</pre> |
</pre> |
||