# Short circuit evaluation vs if

**URL:** <https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [October 3, 2019, 3:22pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453 "2019-10-03T15:22:06Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rajesh\_Talluri](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rajesh_talluri/32/10721_2.png) [@Rajesh\_Talluri](https://discourse.julialang.org/u/Rajesh_Talluri)\
**Post date:** [October 3, 2019, 3:22pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/1 "2019-10-03T15:22:07Z")

</div>

I am trying to understand efficient coding practices looking at source code of released packages and comparing to what I would write. I find some developers use short circuiting instead of an if statement.  
For example in Weave.jl package source

```julia
Base.Meta.isexpr(expr,:(=)) && (options[expr.args[1]] = expr.args[2])
Base.Meta.isexpr(expr,:toplevel) && map(pushopt,fill(options,length(expr.args)),expr.args)

```

There is an example in the docs which encourages this.

```julia
true && (x = (1, 2, 3))

```

vs

```julia
if true 
  x = (1,2,3) 
end

```

Could someone please lend some insight into the advantages/disadvantages of using short circuiting compared to an if statement?

Personally, I think it hinders readability, however I will adopt it if there are other advantages.

---

<div class="post-metadata">

**Author:** ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)\
**Post date:** [October 3, 2019, 3:32pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/2 "2019-10-03T15:32:46Z")

</div>

I mostly find it useful when the if block is just a single line and the condition is somewhat short.

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [October 3, 2019, 3:50pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/3 "2019-10-03T15:50:45Z")

</div>

In addition, `&&` has become kind of common for returning early, eg

```julia
function f(x)
    is_special(x) && return "special"
    y = do_the(x)
    z = rest_of_the(y)
    calculation(y, z)
end

```

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [October 3, 2019, 3:55pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/4 "2019-10-03T15:55:56Z")

</div>

Short circuit evaluation is best applied in these situations:

- between clauses of a compound conditional
- between a simple validation and throwing an exception
- between a state check and an early return

```julia
if x < 0 && y <= 0
  z = x
end

iszero(x) && throw(DomainError("x must be nonzero"))

x == y && return 0.0
return x/y

```

otherwise use an `if` block

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [October 3, 2019, 4:35pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/5 "2019-10-03T16:35:11Z")

</div>

As far as I can tell, it is purely a matter style and taste. Many people who program in Julia like concise code, and the short circuits help with that.

If you prefer `if` blocks for readability, there is no reason not to use that.

---

<div class="post-metadata">

**Author:** ![apo383](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/apo383/32/11272_2.png) [@apo383](https://discourse.julialang.org/u/apo383)\
**Post date:** [October 4, 2019, 7:42pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/6 "2019-10-04T19:42:45Z")

</div>

I am not a fan of `&&` used as a one-liner IF. Julia is great because it’s mostly What You See Is What You Mean, with very little extra cruft. But the one-liner is an idiom, in the sense that it looks like a logical comparison, and only makes sense as IF for those familiar with short-circuiting. I’d like for code just to make sense to anyone, without need for much cultural background. This kind of tricky-cool pattern was pervasive in the bad-old days of Perl, and it makes me cringe to see it in Julia, especially semi-encouraged in the documentation. What You See Is Sensible Only If You Parse Like a Compiler.

If people really want one-liners, why not provide more explicit syntax for that?

`if x==y then return 0.0` instead of `&&`  
`if x==y else return 1.0` instead of `||`

Of course, people should be free to code however they want. But the heavy use of idioms seems to be a sign of demand for syntactical sugar, like an explicit one-liner `if`.

---

<div class="post-metadata">

**Author:** ![greg\_plowman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/greg_plowman/32/8100_2.png) [@greg\_plowman](https://discourse.julialang.org/u/greg_plowman)\
**Post date:** [October 4, 2019, 7:49pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/7 "2019-10-04T19:49:45Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![mbauman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mbauman/32/31082_2.png) [@mbauman](https://discourse.julialang.org/u/mbauman)\
**Post date:** [October 4, 2019, 7:51pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/8 "2019-10-04T19:51:47Z")

</div>

> [@Rajesh\_Talluri](#):
>
> Could someone please lend some insight into the advantages/disadvantages of using short circuiting compared to an if statement?

The two forms produce exactly the same code:

```julia
julia> Meta.@lower test && something()
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope'
1 ─ goto #3 if not test
2 ─ %2 = something()
└── return %2
3 ─ return false
))))

julia> Meta.@lower if test; something(); else false; end
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope'
1 ─ goto #3 if not test
   └
    @ REPL[19]:1 within `top-level scope'
2 ─ %2 = something()
└── return %2
3 ─ return false
))))

```

So the only difference is how it looks to humans. I remember not really liking it at first, but I now really like it, especially for quick defensive argument checks. I still don’t really like it for much more than `test || error()` — in fact I’d favor a PR that changed the doc example you initially cite which uses an assignment to show the side-effect because I don’t think that’s where this feature shines.

---

<div class="post-metadata">

**Author:** ![apo383](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/apo383/32/11272_2.png) [@apo383](https://discourse.julialang.org/u/apo383)\
**Post date:** [October 4, 2019, 8:18pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/9 "2019-10-04T20:18:08Z")

</div>

That’s a nice discussion going back three years, that looks like it might eventually lead to some new syntax! Meanwhile, it would also be nice to provide less encouragement of the short-circuit pattern. It’s fine for the cool kids to use it in their own code, but the documentation could encourage clarity rather than making it seem cool to use it.

https://github.com/JuliaLang/julia/issues/16389

---

<div class="post-metadata">

**Author:** ![Amin\_Yahyaabadi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/amin_yahyaabadi/32/9826_2.png) [@Amin\_Yahyaabadi](https://discourse.julialang.org/u/Amin_Yahyaabadi)\
**Post date:** [October 5, 2019, 4:01am UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/10 "2019-10-05T04:01:56Z")

</div>

There shouldn’t be any difference in terms of speed. I prefer `if` because it is more readable and also more familiar to other programmers.

---

<div class="post-metadata">

**Author:** ![Seif\_Shebl](https://avatars.discourse-cdn.com/v4/letter/s/eada6e/32.png) [@Seif\_Shebl](https://discourse.julialang.org/u/Seif_Shebl)\
**Post date:** [October 5, 2019, 4:23pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/11 "2019-10-05T16:23:10Z")

</div>

I think it’s time for Julia to support one-line conditionals (omitting the `end` keyword) as many old languages do. Compare Fortran and C one liners vs. Julia’s `&&`:

```julia
if (.true.) x = x + 1 # Fortran   
if (true) x += 1; # C
true && (x += 1) # Julia
if true x += 1 # Julia (unsupported)

```

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [October 5, 2019, 4:41pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/12 "2019-10-05T16:41:59Z")

</div>

I’m not sure what you meant by “it’s time”. If anything, the change you propose is a major breaking change (the syntax, as appears on a single line, is valid as is awaiting an `end` in the coming lines) so it’s definately not the right time to do such a change.

Also, I’m not sure what you are trying to show with the comparison of the “one liners”. If you are talking about length, the current julia one is already the shortest. If you just want `if`, then just keep the `end` and it’s a single character longer than the `C` one and still shorter than the fortran one.  
Or if you just don’t like `end`, and I should say I don’t like it either mostly due to the dual use of it in indexing, it’s the property of the language and the `if` isn’t something you should single out on.

---

<div class="post-metadata">

**Author:** ![Seif\_Shebl](https://avatars.discourse-cdn.com/v4/letter/s/eada6e/32.png) [@Seif\_Shebl](https://discourse.julialang.org/u/Seif_Shebl)\
**Post date:** [October 5, 2019, 5:17pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/13 "2019-10-05T17:17:14Z")

</div>

May be I used the wrong expression with the word “time”, I meant at least to be scheduled for the next major version, the discussion at this issue [https://github.com/JuliaLang/julia/issues/16389](https://github.com/JuliaLang/julia/issues/16389) seems to reach at nothing.

Personally, I use `&&` very often for early returns and for throwing exceptions. But, the problem with `true && (x += 1)` for example is that it is not as clear as `if`, especially for new users. And if one drops the parens, it will parse as `(true && x) += 1` which is an invalid assignment.

I don’t also like `end` at the same line with `if`, I see it unnecessary and think it is more suitable for ending a block, besides being used for indexing as you said. I’m not sure though how hard it is to parse the the one-liner if without end.

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [October 5, 2019, 7:04pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/14 "2019-10-05T19:04:04Z")

</div>

As I said, it incompatible with the current parsing

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [October 6, 2019, 8:53am UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/15 "2019-10-06T08:53:16Z")

</div>

Generally, a lot of specific syntactic extensions were proposed to Julia prior 1.0. While some of these may be useful, I think that in general 90% of these should be reviewed and then closed because the extra complexity is not worth the benefit.

While most people (and some style guides) avoid assignents after `&&`, IMO

```julia
condition && return stuff

```

is a perfectly good idiom, and for assignments writing out the multi-line `if` is a feature as it calls attention to changes in values, which may get lost in one-liners, so I would suggest sticking to

```julia
if condition
    x += 1
end

```

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [October 6, 2019, 9:57am UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/16 "2019-10-06T09:57:54Z")

</div>

> [@Rajesh\_Talluri](#):
>
> Could someone please lend some insight into the advantages/disadvantages of using short circuiting compared to an if statement?

One difference that hasn’t been mentioned yet is the interaction with line-based coverage analysis. A one-liner (short-circuit or an if expression written on one line) gives no information whether you have covered the conditional branch, whereas a multi-line if does.

Normally more information is better but it’s a trade-off with other aspects of the code. In particular error exits are not necessarily worth the effort of covering.

---

<div class="post-metadata">

**Author:** ![pauljurczak](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pauljurczak/32/921_2.png) [@pauljurczak](https://discourse.julialang.org/u/pauljurczak)\
**Post date:** [May 24, 2020, 4:52pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/17 "2020-05-24T16:52:56Z")

</div>

I just found this thread a bit late into the game. Learning from Julia manual, I was a bit surprised to see this idiom promoted. My main concern is with this pattern:

```julia
condition || action()

```

which is equivalent to:

```julia
if !condition action() end

```

It seems to be counterintuitive and I’m sure led to an error or two. This is somewhat mitigated by this equivalence:

```julia
if condition else action() end

```

but only a little bit. This leads me to the question: is it accepted in Julia style guides to put a short `if` statement in a single line?

I just noticed an ominous warning `Are you sure you want to continue this old conversation`. I hope it is OK.

---

<div class="post-metadata">

**Author:** ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)\
**Post date:** [May 24, 2020, 6:24pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/18 "2020-05-24T18:24:44Z")

</div>

> [@pauljurczak](#):
>
> I just noticed an ominous warning `Are you sure you want to continue this old conversation` . I hope it is OK.

Most forums prefer users to create new threads than posting to very old threads. The reasons vary, but I think it is mostly because all people of the previous conversation are notified of a new reply and become confused for a moment. Avoid it if possible. Probably there is one or another case it is the best course of action.

> [@pauljurczak](#):
>
> It seems to be counterintuitive and I’m sure led to an error or two.

This is subjective. The notation is entirely natural to me, I read it as “OR this condition is true, OR we need to do this”.

> [@pauljurczak](#):
>
> is it accepted in Julia style guides to put a short `if` statement in a single line?

A style guide is often not enforcing, you can do it. However, I would point that: (1) if you are using an `if` already, you can also use three lines instead of putting the `if` in a single line; (2) the style guide of the specific library you are working with has precedence, [JuMP style guide](http://www.juliaopt.org/JuMP.jl/latest/style/), for example, clearly opposes one recommendation of the Julia Style guide:

> [Use of underscores within names](http://www.juliaopt.org/JuMP.jl/latest/style/#Use-of-underscores-within-names-1)

> The Julia style guide recommends avoiding underscores “when readable”, for example, `haskey` , `isequal` , `remotecall` , and `remotecall_fetch` . This convention creates the potential for unnecessary bikeshedding and also forces the user to recall the presence/absence of an underscore, e.g., “was that argument named `basename` or `base_name` ?”. For consistency, _always use underscores_ in variable names and function names to separate words.

---

<div class="post-metadata">

**Author:** ![pauljurczak](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pauljurczak/32/921_2.png) [@pauljurczak](https://discourse.julialang.org/u/pauljurczak)\
**Post date:** [May 24, 2020, 7:08pm UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/19 "2020-05-24T19:08:03Z")

</div>

> [@Henrique\_Becker](#):
>
> OR we need to do this

I like your reading.

I meant it is a bit counterintuitive or unusual for a C/C++ user. You could write:

```julia
condition || action()

```

in C++ and many other languages with short-circuiting `||`, but I’ve never seen it promoted as an idiom. Maybe it will grow on me. 😀

---

<div class="post-metadata">

**Author:** ![rjmoses](https://avatars.discourse-cdn.com/v4/letter/r/90db22/32.png) [@rjmoses](https://discourse.julialang.org/u/rjmoses)\
**Post date:** [September 7, 2020, 9:35am UTC](https://discourse.julialang.org/t/short-circuit-evaluation-vs-if/29453/20 "2020-09-07T09:35:22Z")

</div>

Joining this thread a little late, but I just started using julia and I like the short circuit evaluation once I figured out what it was.

For readability, I might suggest “condition then statement” since “&&” can easily be misinterpreted. Dropping the false (||) would be okay because !cond accomplishes the same thing.

My two cents…
