# Strange behavior when defining a function inside an \`if\`

**URL:** <https://discourse.julialang.org/t/strange-behavior-when-defining-a-function-inside-an-if/45684>\
**Category:** General Usage\
**Created:** [August 28, 2020, 12:25pm UTC](https://discourse.julialang.org/t/strange-behavior-when-defining-a-function-inside-an-if/45684 "2020-08-28T12:25:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ismedina](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ismedina/32/26433_2.png) [@ismedina](https://discourse.julialang.org/u/ismedina)\
**Post date:** [August 28, 2020, 12:25pm UTC](https://discourse.julialang.org/t/strange-behavior-when-defining-a-function-inside-an-if/45684/1 "2020-08-28T12:25:34Z")

</div>

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

```julia
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
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!

---

<div class="post-metadata">

**Author:** ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)\
**Post date:** [August 28, 2020, 12:29pm UTC](https://discourse.julialang.org/t/strange-behavior-when-defining-a-function-inside-an-if/45684/2 "2020-08-28T12:29:55Z")

</div>

[https://github.com/JuliaLang/julia/issues/15602](https://github.com/JuliaLang/julia/issues/15602)

on Julia nightly you will get a warning.

---

<div class="post-metadata">

**Author:** ![ismedina](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ismedina/32/26433_2.png) [@ismedina](https://discourse.julialang.org/u/ismedina)\
**Post date:** [August 28, 2020, 12:40pm UTC](https://discourse.julialang.org/t/strange-behavior-when-defining-a-function-inside-an-if/45684/3 "2020-08-28T12:40:50Z")

</div>

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!
