# Ifelse() evalutes both cases

**URL:** <https://discourse.julialang.org/t/ifelse-evalutes-both-cases/87525>\
**Category:** General Usage\
**Tags:** function\
**Created:** [September 20, 2022, 3:25pm UTC](https://discourse.julialang.org/t/ifelse-evalutes-both-cases/87525 "2022-09-20T15:25:43Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![kucuksen](https://avatars.discourse-cdn.com/v4/letter/k/a4c791/32.png) [@kucuksen](https://discourse.julialang.org/u/kucuksen)\
**Post date:** [September 20, 2022, 3:25pm UTC](https://discourse.julialang.org/t/ifelse-evalutes-both-cases/87525/1 "2022-09-20T15:25:43Z")

</div>

I have encountered an unexpected (for myself) behavior of the `ifelse()` function. I thought that it would be easier to read if I used `ifelse()` function instead of an if-block. To see the problem that I had consider the following function and its call:

```julia
function foo(x, α)

	ret = ifelse(x < α, log(x), log(-x))

	return ret

end

foo(1.1, 2.0)

```

The call of this function returns a domain error as it tries to evaluate `log(-1.1)` which would not be the case if I used a regular `if-block`. Is it an intended behavior of the `ifelse()` function? I would prefer to use this function for readability purposes but it is not useful for such instances.

---

<div class="post-metadata">

**Author:** ![Per](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/per/32/10387_2.png) [@Per](https://discourse.julialang.org/u/Per)\
**Post date:** [September 20, 2022, 3:30pm UTC](https://discourse.julialang.org/t/ifelse-evalutes-both-cases/87525/2 "2022-09-20T15:30:41Z")

</div>

This is intentional. If you want something that is more compact, but behaves like `if`, then use the ternary operator:

```julia
x < α ? log(x) : log(-x)

```

---

<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:** [September 20, 2022, 3:31pm UTC](https://discourse.julialang.org/t/ifelse-evalutes-both-cases/87525/3 "2022-09-20T15:31:23Z")

</div>

As `ifelse` is a function, its arguments are always evaluated first, as with any function.

---

<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:** [September 20, 2022, 3:35pm UTC](https://discourse.julialang.org/t/ifelse-evalutes-both-cases/87525/4 "2022-09-20T15:35:24Z")

</div>

The `ifelse` function is useful when both expressions are very cheap to evaluate, so cheap that it’s faster to evaluate both than to use an actual brach, which has a certain cost and might even prevent simd vectorization. So it’s primarily used for performance.
