# Function not defined when occurring in else-clause inside of another function

**URL:** <https://discourse.julialang.org/t/function-not-defined-when-occurring-in-else-clause-inside-of-another-function/78106>\
**Category:** General Usage\
**Created:** [March 18, 2022, 7:52pm UTC](https://discourse.julialang.org/t/function-not-defined-when-occurring-in-else-clause-inside-of-another-function/78106 "2022-03-18T19:52:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Geometh](https://avatars.discourse-cdn.com/v4/letter/g/34f0e0/32.png) [@Geometh](https://discourse.julialang.org/u/Geometh)\
**Post date:** [March 18, 2022, 7:52pm UTC](https://discourse.julialang.org/t/function-not-defined-when-occurring-in-else-clause-inside-of-another-function/78106/1 "2022-03-18T19:52:11Z")

</div>

Hi there,

I ran into some weird behavior that I don’t understand. When having two possible function declarations inside an if-else-statement which is wrapped in some outer function, the assignment inside the else-clause doesn’t work. ("Yah, I know that’s bad programming style and I changed my code. However, I would really like to understand what’s going wrong here 😉)

Here is a minimum working example:

```julia
function test(flag=true)
    if flag
        myfunc() = 1
    else
        myfunc() = 0
    end
        println(myfunc())
    return
end

```

Running this function as `test()` or `test(flag=true)` works perfectly fine and prints me a `1`. However, when calling it as `test(flag=false)` the code crashes with `ERROR: UndefVarError: myfunc not defined`.

Why is this happening?

Thank you very much  
G

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [March 18, 2022, 8:41pm UTC](https://discourse.julialang.org/t/function-not-defined-when-occurring-in-else-clause-inside-of-another-function/78106/2 "2022-03-18T20:41:46Z")

</div>

See [JuliaLang/julia#15602](https://github.com/JuliaLang/julia/issues/15602). You need to use anonymous functions:

```julia
function test(flag=true)
    if flag
        myfunc = () -> 1
    else
        myfunc = () -> 0
    end
    println(myfunc())
    return
end

```

---

<div class="post-metadata">

**Author:** ![Geometh](https://avatars.discourse-cdn.com/v4/letter/g/34f0e0/32.png) [@Geometh](https://discourse.julialang.org/u/Geometh)\
**Post date:** [March 19, 2022, 5:24am UTC](https://discourse.julialang.org/t/function-not-defined-when-occurring-in-else-clause-inside-of-another-function/78106/3 "2022-03-19T05:24:42Z")

</div>

thank you
