Variable declaration reset: Difference between revisions

Created Nim solution.
(→‎{{header|Vlang}}: Rename "Vlang" in "V (Vlang)")
(Created Nim solution.)
Line 427:
end
</syntaxhighlight>
 
=={{header|Nim}}==
In Nim, a loop create a new block. Variables declared in the loop body are created and initialized at each round: they do not retain the value from one round to the next.
 
Moreover, a variable needs to be declared before use, except variables in “for” loop which are implicitly declared in the loop block scope. If the variable has not been declared, the program fails to compile.
 
Is is not mandatory to initialize a variable. If there is no explicit initialization, the variable gets a default value which depends on its type (this is a binary zero).
 
Thus, the following program doesn’t compile, as, at compile time, “prev” is used before its declaration:
 
<syntaxhighlight lang="Nim">let s = [1, 2, 2, 3, 4, 4, 5]
for i in 0..s.high:
let curr = s[i]
if i > 0 and curr == prev:
echo i
var prev = curr
</syntaxhighlight>
 
The following program compiles but doesn’t output the right result as “prev” is reset at beginning of each round:
 
<syntaxhighlight lang="Nim">let s = [1, 2, 2, 3, 4, 4, 5]
for i in 0..s.high:
let curr = s[i]
var prev: int
if i > 0 and curr == prev:
echo i
prev = curr
</syntaxhighlight>
 
To get the right result, we need to declare “prev” outside the loop.
<syntaxhighlight lang="Nim">let s = [1, 2, 2, 3, 4, 4, 5]
var prev: int
for i in 0..s.high:
let curr = s[i]
if i > 0 and curr == prev:
echo i
prev = curr
</syntaxhighlight>
 
{{out}}
<pre>2
5
</pre>
 
=={{header|Perl}}==
256

edits