Variable defined - for loop

I know there have been some questions here before on this same topic but I just wanted to note this undefined variable behaviour as strange. Just to clarify this code runs for case 1 and 2, but errors with an undefined variable on case 3. It’s been noted that there’s a workaround where you can state the inner variable as being global, though surely there should be some way to recognize the assign statement is using a variable already in use and default to assigning to the global variable.

x = 1
for y = 1:1
	# Case 1
	# a = x
	# Case 2
	# x = 2
	# Case 3
	x = x
end
println(x)

The kind of behavior wrt scoping that you expect you can find it if you use IJulia, and you will also find it in the REPL when version 1.5 is released.

Compare the current release:
https://docs.julialang.org/en/v1.4/manual/variables-and-scoping/

With forthcoming:

https://docs.julialang.org/en/v1.5-dev/manual/variables-and-scoping/

1 Like