Scope of variable in if in loop

The behavior you see is the expected behavior. The if statement does not create a new scope, but the for creates a new scope for each iteration. So b will never be defined inside any loop besides the first. You need to declare it one scope above for your code to work (i.e., outside the for).

I wrote a better answer to a very similar question in the past: I thought I understood "pass-by-sharing" in Julia until I found this - #19 by Henrique_Becker

12 Likes