On loop scoping, inside functions

I know, this topic again. After a year I thought I understood this well enough, I was wrong. I expect this to work but it doesn’t. I don’t want to declare b as a global here, just access it inside the function.

function foo()
    for i in 1:10
        b=rand()
    end
    print(b)
end

But it works if I initialize it…why?

function bar()
    b=undef
    for i in 1:10
        b=rand()
    end
    print(b)
end

I see how this particular example is not covered in Scope of Variables · The Julia Language , but if you look closely into the local scope section, there’s an example that starts with

Let’s dig into the fact that the for loop body has its own scope for a second…

You see there, that in the for loop a new local variable t is defined. The same is happening in your example, where you define a new variable b local to the for loop in each iteration. Then, similar to t in the documentation, it is not available outside the loop.

2 Likes

You can also use local b instead of b = undef before executing the loop. This has the advantage of a linter in your IDE being able to tell you that b isn’t assigned to one some path, should that be the case. You won’t run into the problem of spuriously seeing some undef somewhere you didn’t expect.

2 Likes

I wonder if this has performance hit because of type instability, compare to local