# Overwriting functions in conditional statements

**URL:** <https://discourse.julialang.org/t/overwriting-functions-in-conditional-statements/9459>\
**Category:** General Usage\
**Tags:** question\
**Created:** [March 2, 2018, 4:22pm UTC](https://discourse.julialang.org/t/overwriting-functions-in-conditional-statements/9459 "2018-03-02T16:22:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![brossetti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brossetti/32/26114_2.png) [@brossetti](https://discourse.julialang.org/u/brossetti)\
**Post date:** [March 2, 2018, 4:22pm UTC](https://discourse.julialang.org/t/overwriting-functions-in-conditional-statements/9459/1 "2018-03-02T16:22:10Z")

</div>

I’m looking for some confirmation or correction about an interesting (to me) behavior I came across when defining functions inside conditional statements. Here’s a quick example:

```julia
julia> function test(x)
       if (x == 1)
           fn() = "this"
       elseif (x == 2)
           fn() = "that"
       else
           fn() = "the other"
       end
       fn()
       end

julia> test(1)
"the other"

julia> test(2)
ERROR: UndefVarError: fn not defined
Stacktrace:
 [1] test(::Int64) at ./REPL[44]:9

```

Someone coming from MATLAB might expect the following results:

```julia
julia> test(1)
"this"

julia> test(2)
"that"

```

Two Questions:

1. Am I correct that the difference in behavior is related to compiled vs interpreted?
2. Is there a way to get the MATLAB-like behavior in julia?

Thanks!

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [March 2, 2018, 4:30pm UTC](https://discourse.julialang.org/t/overwriting-functions-in-conditional-statements/9459/2 "2018-03-02T16:30:45Z")

</div>

> [@brossetti](#):
>
> Am I correct that the difference in behavior is related to compiled vs interpreted?  
> Is there a way to get the MATLAB-like behavior in julia?

No, this is because you’re defining named functions which are global in somce sense. In MATLAB you’d use function handles which is akin to Julia’s anonymous functions.

```julia
function test(x)
       if (x == 1)
           fn = ()->"this"
       elseif (x == 2)
           fn = ()->"that"
       else
           fn = ()->"the other"
       end
       fn()
       end
```

---

<div class="post-metadata">

**Author:** ![brossetti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/brossetti/32/26114_2.png) [@brossetti](https://discourse.julialang.org/u/brossetti)\
**Post date:** [March 2, 2018, 4:37pm UTC](https://discourse.julialang.org/t/overwriting-functions-in-conditional-statements/9459/3 "2018-03-02T16:37:38Z")

</div>

Perfect, thanks for the clarification.
