Strange behavior when defining a function inside an `if`

Hi! I have encountered this weird behavior when using Julia. If I define:

function f(x)
    if x > 0
        function g()
            1
        end
        return g
    else
        function g()
            0
        end
        return g
    end
end

I expect that f(1) yields a function g that is constantly 1, while f(0) would yield a function g that is constantly 0. But I get the following:

julia> g = f(1); g()
0

julia> g = f(0); g()
ERROR: UndefVarError: g not defined
Stacktrace:
 [1] f(::Int64) at ./REPL[15]:11
 [2] top-level scope at none:0

So in the first case it took the wrong if branch, while in the second it is even worse, as if g wasn’t defined. Can you help me understand what is happening? Thanks!

on Julia nightly you will get a warning.

1 Like

Mmmm I see. Makes sense that it is disallowed. Still I think some warning is missing; I was testing that in 1.5.

Thanks a lot!