Skip to content

Commit

Permalink
Merge pull request JuliaLang#9516 from tlycken/master
Browse files Browse the repository at this point in the history
Clarify scoping of if blocks
  • Loading branch information
ViralBShah committed Jan 1, 2015
2 parents 28feafd + f7f0e05 commit b4fc186
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
33 changes: 33 additions & 0 deletions doc/manual/control-flow.rst
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,39 @@ blocks as desired can be used. The condition expressions in the
evaluates to ``true``, after which the associated block is evaluated,
and no further condition expressions or blocks are evaluated.

``if`` blocks are "leaky", i.e. they do not introduce a local scope.
This means that new variables defined inside the ``ìf`` clauses can
be used after the ``if`` block, even if they weren't defined before.
So, we could have defined the ``test`` function above as

.. doctest::

julia> function test(x,y)
if x < y
relation = "less than"
elseif x == y
relation = "equal to"
else
relation = "greater than"
end
println("x is ", relation, " than y.")
end

``if`` blocks also return a value, which may seem unintuitive to users
coming from many other languages. This value is simply the return value
of the last executed statement in the branch that was chosen, so

.. doctest::

julia> x = 3

julia> if x > 0
"positive!"
else
"negative..."
end
"positive!"

Note that very short conditional statements (one-liners) are frequently expressed using
Short-Circuit Evaluation in Julia, as outlined in the next section.

Expand Down
2 changes: 1 addition & 1 deletion doc/manual/variables-and-scoping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ The constructs introducing such blocks are:
- ``type`` blocks.

Notably missing from this list are
:ref:`begin blocks <man-compound-expressions>`, which do
:ref:`begin blocks <man-compound-expressions>` and :ref:`if blocks <man-conditional-evaluation>`, which do
*not* introduce new scope blocks.

Certain constructs introduce new variables into the current innermost
Expand Down

0 comments on commit b4fc186

Please sign in to comment.