navneethc
navneethc

Reputation: 1466

Why does Julia not print `false` inside a conditional?

Julia 1.4.2

The behaviour that stumps me occurs in the first and fourth cases:

julia> if (val = (1 == 2))
           println(val)
       end

julia> if (val = (1 == 1))
           println(val)
       end
true

julia> if (val = (1 == 1))
           println(val + 5)
       end
6

julia> if (val = (1 == 2))
           println(val + 5)
       end

julia> 1 == 2
false

julia> 1 == 1
true

julia> println(1==2)
false

julia> println(1==1)
true

I observe this in the REPL and in Jupyter.

My questions are:

  1. Why does this happen?
  2. How can I retrieve the value of val, preferably the "truthy" value, in both cases?

Upvotes: 4

Views: 151

Answers (1)

Let's look at the first example in more details

# initially, `val` does not exist
julia> val
ERROR: UndefVarError: val not defined

# 1==2 is false
# the assignment returns the value of the right-hand side -> false
julia> if (val = (1 == 2))
           # therefore, this branch is not taken
           println(val)
       else
           # but this one is
           println("in the else clause")
       end
in the else clause

# `if` returns whatever the branch taken evaluates to.
# In this case, `println` returns nothing, so the `if` block does not
# return anything either
julia> @show ans
ans = nothing

# `if` doesn't introduce a new scope, so the newly created `val` variable
# can still be inspected
julia> val
false

Upvotes: 4

Related Questions