<p>The ternary &quot;if&quot; operator is a syntactic construct for returning one of two values based upon a boolean condition. In most C-family languages its syntax resembles <code>condition ? ifTrue : ifFalse</code>. Some other languages, like Python, use syntax like <code>ifTrue if condition else ifFalse</code> or <code>if condition ifTrue else ifFalse</code>. What are popular options for syntax, and what are their advantages and disadvantages?</p>

<syntax><language-comparison><operators><conditional>
What are the syntax options for implementing a ternary "if" operator?
<p>In an expression-oriented language such as Rust:</p>
<pre><code>result = if condition { ifTrue } else { ifFalse }
</code></pre>

CC BY-SA 4.0
2023-05-16T18:28:02.097Z
2023-05-16T18:28:02.097Z
CPlus
<p>One option is SQL's <code>CASE WHEN foo THEN bar ELSE baz END</code>. Advantages, in addition to the very clear syntax, are that it also can  be used as a binary operator <code>CASE WHEN foo THEN bar END</code> (defaulting to <code>NULL</code>) and as a superternary operator:</p>
<pre><code>CASE
    WHEN foo THEN 1
    WHEN bar THEN 2
    WHEN baz THEN 3
    ELSE -1
END
</code></pre>
<p>The only disadvantage I can see is its verbosity, requiring 8 tokens in the ternary case instead of the 5 tokens of the less verbose languages.</p>

CC BY-SA 4.0
2023-07-06T08:06:23.517Z
2023-07-06T13:42:45.007Z
2023-07-06T13:42:45.007Z
Egyptian Natural Gas Company
CC BY-SA 4.0
2023-07-06T09:53:53.883Z
This does not appear to answer the asked question
Starship
CC BY-SA 4.0
2023-07-07T13:36:53.337Z
@Starship-OnStrike How so? The first example does exactly the same thing as `foo ? bar : baz`  in C-like languages. A language designer could choose to limit the syntax to the ternary case or to support non-ternary usage as well.
Egyptian Natural Gas Company
<p>One interesting option, if your language has an <code>Optional</code> type, is to forgo having a traditional conditional expression structure entirely, but instead have operators designed for working with <code>Optional</code>s to achieve the same results conveniently:</p>
<ul>
<li><code>c ? e</code> would mean &quot;if <code>c</code> evaluates to true, then the <code>Optional</code> containing the result of evaluating <code>e</code>, otherwise the empty <code>Optional</code>&quot;</li>
<li><code>o : a</code> would mean &quot;if <code>o</code> is a non-empty <code>Optional</code> then its content, otherwise the result of evaluating <code>a</code>&quot;</li>
</ul>
<p>These two simple operations combine together to give the same behaviour as a C-style expression of the same form, and in most circumstances a relatively simple optimizer should be able to eliminate the creation of the Optional object, giving the same performance as a direct implementation.  They simplify parsing because you no longer need a special case for a ternary operator.</p>
<p>Note that because these operators have arguments that are <em>expressions</em> and they need to be able to control whether or not these expressions are evaluated, they either need to be language-level constructs (rather than simply defined using an operator overloading facility) or you need some other special faciity that allows arbitrarily short-circuiting evaluation (e.g. lazy evaluation or some kind of macro system that can operate on expressions as arguments)</p>
<p>Other syntaxes are, of course, also possible with similar semantics, e.g.:</p>
<pre><code>Optional.ifTrue(c, e).orElse(a)
</code></pre>
<p>(which looks a bit like Java, but can't be implemented in Java for the reasons explained above)</p>

CC BY-SA 4.0
2023-07-12T20:10:48.290Z
2023-07-12T20:18:42.193Z
2023-07-12T20:18:42.193Z
occipita
CC BY-SA 4.0
2024-09-18T21:51:47.330Z
Or you could make an `Optional` unit type your language’s Boolean, and `map` the `const` function to it..
Davislor
<p>There's the Lisp style:</p>
<pre><code>(IF condition then-expression [else-expression])
</code></pre>
<p>Lisp doesn't distinguish between statements and expressions, so this is both an if-statement and a ternary.</p>
<p>It's also a specialization of the more general <code>COND</code>:</p>
<pre><code>(cond
    (condition1 body1...)
    (condition2 body2...)
    ...
    [(t else-body)]
)
</code></pre>

CC BY-SA 4.0
2023-07-11T02:01:00.300Z
2023-07-11T02:01:00.300Z
Barmar
<p>There are three clauses, which can be permuted six ways:</p>
<ul>
<li><code>if P then A else B</code></li>
<li><code>A if P else B</code></li>
<li><code>A else B if P</code></li>
<li><code>if P fails B otherwise A</code></li>
<li><code>B unless P then A</code></li>
<li><code>B except A if P</code></li>
</ul>
<p>There are four slots in which to stick a piece of syntax (before, after, between the first and second, and between the second and third). In the examples above, I either put a keyword before each clause, or keywords between two clauses, but you can spell these however you like.</p>
<p>You could take a page from ML-family languages:</p>
<pre class="lang-none prettyprint-override"><code>if p a b
</code></pre>
<p>But a stack-based language in RPN could be even more terse:</p>
<pre class="lang-none prettyprint-override"><code>BAP?
</code></pre>
<p><strong>Edit:</strong> This one actually does have implications for the semantics.  If there is no syntax separating the two branches explicitly, efficient short-circuiting is only possible if the runtime can figure out which commands are part of each branch of the tree statically, without evaluating both.  So, for example, we can’t have a <code>Σ</code> command that pops the number of terms to add together off the stack, then consumes that number of terms from the stack.  It would then be impossible to determine which tokens not to evaluate, without evaluating them.</p>
<p>Instead of keywords, you might use the offsides rule:</p>
<pre class="lang-none prettyprint-override"><code>ifThenElse p
   A
   B
</code></pre>
<p>Although it’s handy to be able to write these as a one-liner too.  if you want these to be options, there should generally be some transformation between lists using indentation and those using separators.</p>

CC BY-SA 4.0
2023-07-10T23:14:45.617Z
2023-07-12T16:20:14.823Z
2023-07-12T16:20:14.823Z
Davislor
CC BY-SA 4.0
2023-07-11T01:43:01.633Z
If the expression requires exploiting the offside rule in a language that already ascribes meaning to that, it doesn't seem to have any real point - certainly it doesn't appear to have much of an advantage over actually using an `if` statement. This sort of thing also doesn't embed neatly as a subexpression of more complex expressions.
Karl Knechtel
CC BY-SA 4.0
2023-07-11T01:57:27.010Z
In stack-based languages (and some others), on the other hand, the distinction between statements and expressions may well be moot. Still, I like this answer for the comprehensive overview of ways to construct the syntax.
Karl Knechtel
CC BY-SA 4.0
2023-09-02T00:47:06.757Z
For stack-based languages, you have FORTH, which use `IF iftrue ELSE iffalse THEN`, with the condition taken from the stack before the IF.  The code in either the iftrue or iffalse will be executed and can do whatever it wants with the stack (consume values or push new ones), though the results can be difficult to understand if the two cases don't have the same delta stack depth.
Chris Dodd
<p><a href="/questions/tagged/ruby" class="post-tag" title="show questions tagged &#39;ruby&#39;" aria-label="show questions tagged &#39;ruby&#39;" rel="tag" aria-labelledby="tag-ruby-tooltip-container">ruby</a></p>
<p>Ruby does not distinguish between statements and expressions – everything is an expression. Therefore, the traditional <code>if</code>/<code>then</code>/<code>else</code> can be used as an expression.</p>
<p>It is typically written as:</p>
<pre class="lang-ruby prettyprint-override"><code>if condition
  consequence1
elsif other_condition
  consequence2
else
  consequence3
end
</code></pre>
<p>However, the line break to separate the condition from the consequence can also be written as a semicolon <code>;</code> or as the keyword <code>then</code>, so the following are also both valid (and semantically equivalent):</p>
<pre class="lang-ruby prettyprint-override"><code>if condition then consequence1 elsif other_condition then consequence2 else consequence3 end

if condition; consequence1 elsif other_condition; consequence2 else consequence3 end
</code></pre>
<p>Ruby <em>also</em> has the ternary conditional operator <code>condition ? consequence1 : consequence3</code>, but I personally consider it superfluous. The conditional operator's precedence in combination with Ruby allowing the leave out parentheses around argument lists in message sends also sometimes surprises programmers, whereas substituting the conditional expression into the same piece of code has the expected precedence.</p>

CC BY-SA 4.0
2023-07-01T07:34:50.117Z
2023-07-01T07:34:50.117Z
Jörg W Mittag
<p>Ada has conditional expressions if is one, case is another, they enclosed in parenthesis:</p>
<pre><code>(if Casey.Sex = M then &quot;Male&quot; else &quot;Female&quot;)
</code></pre>
<p>from the <a href="http://www.ada-auth.org/standards/22rm/html/RM-4-5-7.html" rel="nofollow noreferrer">Ada 2022 RM</a>.</p>

CC BY-SA 4.0
2023-05-19T14:13:20.437Z
2023-05-19T14:13:20.437Z
Luke A. Guest
<p>An option I haven't seen is to preserve the order of C-like languages, but using keywords: <code>condition then ifTrue else ifFalse</code>. (This could also be described as &quot;F# syntax, but without the leading <code>if</code>&quot;.)</p>

CC BY-SA 4.0
2023-07-07T01:46:59.587Z
2023-07-07T01:46:59.587Z
Karl Knechtel
<p>If your language supports lazy evaluation, <code>if</code> can be a regular function instead of a special form.</p>
<p>For example, in Mathematica, <code>If</code> is simply a built-in function that takes three arguments:</p>
<pre><code>If[condition, t, f]
</code></pre>
<p>This function has the attribute <code>HoldRest</code>, which means that the arguments except the first one are not evaluated before the function is called.</p>
<p>Haskell also supports lazy evaluation, and you can define your own <code>if</code> function easily. I don't know why it chooses to use a special syntax for <code>if</code> instead of a function.</p>

CC BY-SA 4.0
2023-05-17T03:39:02.790Z
2023-05-17T03:39:02.790Z
alephalpha
CC BY-SA 4.0
2023-07-06T15:43:55.093Z
In Haskell, it's probably for readability: `if f x then g y else h z` is more readable than `if (f x) (g y) (h z)`.
xigoi
CC BY-SA 4.0
2023-07-06T15:50:48.160Z
@xigoi Personally, I find the latter more readable.
user76284
CC BY-SA 4.0
2023-07-11T21:48:05.447Z
TSQL and VB implement it as a function this way, named `IIF` for `Inline If`
James
CC BY-SA 4.0
2023-07-15T02:14:42.243Z
There's a page on the Haskell wiki about this: https://wiki.haskell.org/If-then-else. (I agree that a plain function would be better.) Feel free to link to it to your answer.
user76284
CC BY-SA 4.0
2023-07-15T03:00:43.813Z
This can also be done in strict languages (see [my answer](https://langdev.stackexchange.com/a/2399/1368)).
user76284
<p>Stack based langauges that directly use RPN tend to have quite different syntaxes for conditionals, built up from their underlying stack operations.</p>
<hr />
<p>In <a href="https://en.wikipedia.org/wiki/Forth_%28programming_language%29" rel="nofollow noreferrer">FORTH</a>, you have words that compile directly to (conditional) branches and branch targets:</p>
<ul>
<li><code>IF</code>: pop stack and conditional branch forward if value popped is 0 (false)</li>
<li><code>ELSE</code>: unconditional forward branch + target of last unresolved IF branch</li>
<li><code>THEN</code>: target of last unresolved IF or ELSE branch</li>
</ul>
<p>That gives you code that looks like</p>
<p><em>cond</em> <code>IF</code> <em>iftrue</em> <code>ELSE</code> <em>iffalse</em> <code>THEN</code></p>
<p>where <em>cond</em> is RPN code that leaves a boolean value on the stack, after which either the <em>iftrue</em> or <em>iffalse</em> code will run depending on whether that value was non-zero or zero.</p>
<hr />
<p>In <a href="https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf" rel="nofollow noreferrer">Postscript</a>, things are built around the <code>{</code>...<code>}</code> construct that compiles stored procedures -- any code in curly braces is compiled and a reference to the compiled code is pushed on the stack.  That gives you code that looks like</p>
<p><em>cond</em> <code>{</code><em>iftrue</em><code>}</code> <code>{</code><em>iffalse</em><code>}</code> <code>ifelse</code></p>
<p>where <code>ifelse</code> just pops three things from the stack (condition and two stored procedure refs) and executes one of the stored procedures.  If either of the latter is <em>not</em> a stored procedure, it will just be pushed back on the stack, so if you just want a value in either slot (rather than actual conditional execution), the braces are unneeded.</p>

CC BY-SA 4.0
2023-09-02T23:27:42.363Z
2023-09-04T00:03:12.347Z
2023-09-04T00:03:12.347Z
Chris Dodd
<p>The conditional operator can be implemented without any special syntax or semantics beyond those of ordinary functions, even in <a href="https://en.wikipedia.org/wiki/Strict_programming_language" rel="nofollow noreferrer">strict languages</a>.</p>
<p>In <a href="https://en.wikipedia.org/wiki/Lambda_calculus" rel="nofollow noreferrer">lambda calculus</a> notation, let</p>
<pre><code>id = λa.a
true = λa.λb.a
false = λa.λb.b
if = λp.λa.λb.p a b id
</code></pre>
<p>Then, for example:</p>
<pre><code>if true (λx.then) (λx.else)
→ true (λx.then) (λx.else) id
→ (λx.then) id
→ then
</code></pre>
<p>Note that the branches are wrapped in <a href="https://en.wikipedia.org/wiki/Thunk" rel="nofollow noreferrer">thunks</a> to prevent their contents from being evaluated eagerly.</p>

CC BY-SA 4.0
2023-07-15T02:59:11.150Z
2023-07-15T02:59:11.150Z
user76284
<p>C# switch expression is almost directly analogous to SQL’s case expression.</p>
<p>Both can do exactly what a ternary expression does.</p>
<pre><code>bool b = f(1);
var result = b switch  
{  
    true =&gt; &quot;One&quot;,  
    false =&gt; &quot;Two&quot;,
}; 
</code></pre>
<p>But are more powerful because they are not limited to just a single condition and so are easier to read with multiple conditions.</p>
<pre><code>var result = i switch  
{  
    1 when y==2 =&gt; &quot;One&quot;,  
    1 when y&gt;4  =&gt; &quot;Two&quot;,  
    3 =&gt; &quot;Three&quot;,  
    44 =&gt; &quot;Forty Four&quot;,  
}; 

<span class="math-container">```</span>
</code></pre>

CC BY-SA 4.0
2023-09-10T19:13:43.413Z
2023-09-11T11:29:05.413Z
2023-09-11T11:29:05.413Z
jmoreno
CC BY-SA 4.0
2023-09-10T22:37:45.590Z
This isn't a syntax option for a ternary/conditional expression, it's a different language construct.
kaya3
CC BY-SA 4.0
2023-09-11T00:05:23.630Z
@kaya3: a ternary expression is just a switch expression which requires exactly 2 values, instead of 1 or more.
jmoreno
CC BY-SA 4.0
2023-09-11T15:54:24.347Z
@kaya3's point still stands
Seggan
CC BY-SA 4.0
2023-09-11T16:36:01.297Z
@Seggan: look at my first example again, and tell me how it is not a ternary -- if the language description for that said "syntactic construct for returning one of two values based upon a boolean".  True, I am pointing out that it would be better to describe it as "syntactic construct for returning one of N values based upon the first matching condition", but it's a valid syntax for a ternary.
jmoreno
CC BY-SA 4.0
2023-09-11T16:56:02.943Z
@Seggan: if you include the requirement that true has to come before false, then there is nothing that can be done with a C-family ternary that can't be done with that syntax, and nothing can be done with that syntax that can't be done with a C-family ternary.  They are 100% matches.
jmoreno
CC BY-SA 4.0
2023-09-11T17:07:24.447Z
(1) As I said, it's a different language construct; the fact that you can use it as a substitute for a ternary expression does not make it a syntax option for a ternary expression; (2) If you are proposing this as a syntax option for a ternary expression, it's a pretty bad option. It's rather verbose since it spells out `true` and `false` as well as all the other punctuation; and I don't think any major style guide would recommend this, even in languages which lacked a proper ternary conditional operator.
kaya3
CC BY-SA 4.0
2023-09-11T21:42:59.333Z
@kaya3: Not an answer. Also bad answer. Also violates style guide for unspecified language.  Gotcha
jmoreno
<p>VB.Net also features a fairly decent approach that is similar to R's approach (which was mentioned in <a href="https://languagedesign.stackexchange.com/a/87/30">this answer</a>). There are two syntaxes:</p>
<ul>
<li><p><code>result = IIf(expression, trueresult, falseresult)</code></p>
</li>
<li><p><code>result = If(expression, trueresult, falseresult)</code></p>
</li>
</ul>
<p>The lattermost form was added later than the former, and obviously differs only by a letter, but has parity with the existing <code>If</code> syntax for ordinary if statements.</p>

CC BY-SA 4.0
2023-05-16T18:45:16.200Z
2023-05-16T18:45:16.200Z
Spevacus
<p>Here are some options (including the ones you mentioned):</p>
<ul>
<li><p><strong>C-family languages (e.g., C, C++, Java, JavaScript):</strong> <br />
Syntax: <code>condition ? ifTrue : ifFalse</code></p>
<ul>
<li>Advantage: This syntax is widely adopted and familiar to developers working with C-family languages. It is concise and expressive.</li>
<li>Disadvantage: It could be a bit less readable than other options, like Python, especially as it doesn't have the keywords <code>if</code> and <code>else</code>. It also creates ambiguity with other operators like the trailing <code>?</code> operator.</li>
</ul>
</li>
<li><p><strong>Python:</strong> <br />
Syntax: <code>ifTrue if condition else ifFalse</code></p>
<ul>
<li>Advantage: The Python syntax reads naturally, resembling a sentence. It can be more readable, especially when the expressions within the ifTrue and ifFalse branches are longer.</li>
<li>Disadvantage: The order of ifTrue and ifFalse might be less intuitive for developers accustomed to other languages' ternary syntax. The difference in syntax may lead to errors when transitioning between languages. It's also not the same order as a normal <code>of</code> statement. Also, the first thing to be evaluated is the <code>condition</code> in the middle, which might be a bit counter-intuitive.</li>
</ul>
</li>
<li><p><strong>R/Excel:</strong> <br />
Syntax: <code>ifelse(condition, ifTrue, ifFalse)</code></p>
<ul>
<li>Advantage: It's a lot clearer if you have multiple nested conditions, because in the alternatives you would have to insert parentheses for readability. <br />
(Think <code>a ? b ? c : d : e</code> vs. <code>ifelse(a, ifelse(b, c, d), e)</code>)</li>
<li>Disadvantage: It doesn't actually have the keywords <code>if</code> and <code>else</code> next to <code>ifTrue</code> and <code>ifFalse</code>, so it could appear less readable.</li>
</ul>
</li>
<li><p><strong>Scala 2/Kotlin:</strong> <br />
Syntax: <code>if (condition) ifTrue else ifFalse</code></p>
<ul>
<li>Advantage: It's in the same order as basically every language's normal <code>if</code> statement, so it seems more natural.</li>
<li>Disadvantage: You have to write out parentheses around the condition, which is not required in any other syntax mentioned here.</li>
</ul>
</li>
<li><p><strong>Swift/Rust:</strong> <br />
Syntax: <code>if condition { ifTrue } else { ifFalse }</code></p>
<ul>
<li>Advantage: Exactly like a normal <code>if</code> statement in most languages. This makes it more natural to write.</li>
<li>Disadvantage: Two pairs of brackets in a ternary operator?! Are you kidding me?</li>
</ul>
</li>
<li><p><strong>F#/Scala 3:</strong> <br />
Syntax: <code>if condition then ifTrue else ifFalse</code></p>
<ul>
<li>Advantage: Once again, in the order of a normal <code>if</code> statement, making it more natural.</li>
<li>Disadvantage: Seems quite verbose, especially if they're nested.</li>
</ul>
</li>
<li><p><strong>Nim:</strong> <br />
Syntax: <code>if condition: ifTrue else: ifFalse</code></p>
<ul>
<li>Advantage: Exactly like a normal <code>if</code> statement, so it's very natural.</li>
<li>Disadvantage: Not too bad, but it still does need the keywords <code>if</code> and <code>else</code> along with two colons.</li>
</ul>
</li>
</ul>

CC BY-SA 4.0
2023-05-16T18:24:26.157Z
2023-09-02T10:05:35.870Z
2023-09-02T10:05:35.870Z
The Thonnu
CC BY-SA 4.0
2023-05-18T01:14:03.467Z
... How can R call functions without fully evaluating their arguments first?
Karl Knechtel
CC BY-SA 4.0
2023-05-18T05:48:46.883Z
@KarlKnechtel I'm not too sure, you'll have to ask an R expert for that.
The Thonnu
CC BY-SA 4.0
2023-05-19T00:32:49.603Z
Scala 3 also permits if condition then ifTrue else ifFalse.
prosfilaes
CC BY-SA 4.0
2023-07-01T07:26:22.607Z
@KarlKnechtel: It's called *lazy evaluation*. Most popular languages are *eager* by default, but there are some (e.g. Haskell) which are lazy by default. Some languages which are eager by default still allow lazy evaluation as an option (e.g. Scala). Even languages that don't, often have some builtin constructs which are lazy, for example, in many languages the boolean operators are lazy in their right operand. In R, specifically, [function arguments are *Promises*](https://cran.r-project.org/doc/manuals/r-devel/R-lang.html#Argument-evaluation). See https://langdev.stackexchange.com/a/275/854
Jörg W Mittag
CC BY-SA 4.0
2023-07-06T15:34:56.513Z
Nim: `if condition: ifTrue else: ifFalse`
xigoi
CC BY-SA 4.0
2023-07-07T00:40:15.273Z
Excel also uses the R syntax
Seggan
CC BY-SA 4.0
2023-07-13T17:27:39.383Z
Another downside of the Python system is that it has a confusing right-to-left evaluation order, differing from the rest of the language. Evaluation of the condition in the middle happens first, then evaluation of "ifTrue" may happen second.
isaacg
CC BY-SA 4.0
2023-07-14T20:38:33.100Z
Python's `A if X else B` isn't non-intuitive (only) because of other languages, but also because it doesn't follow the structure of a regular `if`-statement _in Python itself_.
ilkkachu
CC BY-SA 4.0
2023-05-16T18:27:07.660Z
Swift: parens optional, but braces required — `if a { b } else { c }`. This syntax had been used solely for statements for a while (opting for C’s `?:` for the expression), but was recently approved for expressions as well.
Bbrk24
CC BY-SA 4.0
2023-05-16T18:27:44.810Z
The problem with `if condition ifTrue else ifFalse` is that `condition ifTrue` would, in many languages, be ambiguous, since e.g. `f(g)` is a valid expression but `f` and `(g)` are also valid expressions by themselves. Scala's solution using brackets is not the only option ─ Rust has `if condition {ifTrue} else {ifFalse}`, and F# has `if condition then ifTrue else ifFalse`.
kaya3
CC BY-SA 4.0
2023-05-16T18:31:30.507Z
Another disadvantage of `?` and `:` is the ambiguity it creates with other common syntax, like trailing `?` operators
rydwolf
CC BY-SA 4.0
2023-05-16T20:42:02.243Z
An advantage for the Rust syntax (not sure if it applies to Swift as well) is that the ifTrue and ifFalse sections are complete blocks, so they can have their own scope for internal required calculations instead of being a single expression.
kouta-kun
CC BY-SA 4.0
2023-05-17T00:47:31.123Z
The R syntax looks like a function call; does it short-circuit?
Karl Knechtel
CC BY-SA 4.0
2023-05-17T01:40:53.100Z
Or don't have a ternary operator at all.
naffetS
CC BY-SA 4.0
2023-05-17T04:11:21.790Z
I wouldn't consider it reasonable to criticise F# here, because there is no "normal if statement"  - because F# is expression based, that is the only if-else construct in the language. To call it verbose is to call a normal C style if statement verbose - while true, not quite reasonable when comparing it to a ?: ternary.
blueberry
CC BY-SA 4.0
2023-05-17T04:11:37.130Z
@kouta-kun Swift distinguishes *`if` statements* (where the branches are full blocks) and *`if` expressions* (where each branch must be a single expression).
Bbrk24
CC BY-SA 4.0
2023-05-17T05:30:07.183Z
@KarlKnechtel yes, it's both a function call and short-circuit: [Attempt This Online](https://ato.pxeger.com/run?1=m72waMGCpaUlaboW-zLTUnOKUzUMbYx0FAx0FAqKMvNKNJQyUnNy8pU0NSGKoGphegA)
The Thonnu
<p>There's always the Smalltalk postfix form.</p>
<pre><code>result = condition ifTrue: [ ... ] ifFalse: [ ... ].
</code></pre>
<p>This has the benefit of not even being special syntax. It's just an ordinary application of the <code>ifTrue:ifFalse:</code> method on a Boolean object.</p>

CC BY-SA 4.0
2023-05-16T18:32:50.247Z
2023-05-16T18:32:50.247Z
Silvio Mayolo
# What are the syntax options for implementing a ternary "if" operator?
Posted by: username_0 on 2023-05-16
The ternary "if" operator is a syntactic construct for returning one of two values based upon a boolean condition. In most C-family languages its syntax resembles `condition ? ifTrue : ifFalse`. Some other languages, like Python, use syntax like `ifTrue if condition else ifFalse` or `if condition ifTrue else ifFalse`. What are popular options for syntax, and what are their advantages and disadvantages?
**Tags:** syntax language-comparison operators conditional
---
## 15 answers
### Answer by username_19 on 2023-05-16. Score: 20 | Accepted answer
Here are some options (including the ones you mentioned):

* **C-family languages (e.g., C, C++, Java, JavaScript):**   
  Syntax: `condition ? ifTrue : ifFalse`

  + Advantage: This syntax is widely adopted and familiar to developers working with C-family languages. It is concise and expressive.
  + Disadvantage: It could be a bit less readable than other options, like Python, especially as it doesn't have the keywords `if` and `else`. It also creates ambiguity with other operators like the trailing `?` operator.
* **Python:**   
  Syntax: `ifTrue if condition else ifFalse`

  + Advantage: The Python syntax reads naturally, resembling a sentence. It can be more readable, especially when the expressions within the ifTrue and ifFalse branches are longer.
  + Disadvantage: The order of ifTrue and ifFalse might be less intuitive for developers accustomed to other languages' ternary syntax. The difference in syntax may lead to errors when transitioning between languages. It's also not the same order as a normal `of` statement. Also, the first thing to be evaluated is the `condition` in the middle, which might be a bit counter-intuitive.
* **R/Excel:**   
  Syntax: `ifelse(condition, ifTrue, ifFalse)`

  + Advantage: It's a lot clearer if you have multiple nested conditions, because in the alternatives you would have to insert parentheses for readability.   
    (Think `a ? b ? c : d : e` vs. `ifelse(a, ifelse(b, c, d), e)`)
  + Disadvantage: It doesn't actually have the keywords `if` and `else` next to `ifTrue` and `ifFalse`, so it could appear less readable.
* **Scala 2/Kotlin:**   
  Syntax: `if (condition) ifTrue else ifFalse`

  + Advantage: It's in the same order as basically every language's normal `if` statement, so it seems more natural.
  + Disadvantage: You have to write out parentheses around the condition, which is not required in any other syntax mentioned here.
* **Swift/Rust:**   
  Syntax: `if condition { ifTrue } else { ifFalse }`

  + Advantage: Exactly like a normal `if` statement in most languages. This makes it more natural to write.
  + Disadvantage: Two pairs of brackets in a ternary operator?! Are you kidding me?
* **F#/Scala 3:**   
  Syntax: `if condition then ifTrue else ifFalse`

  + Advantage: Once again, in the order of a normal `if` statement, making it more natural.
  + Disadvantage: Seems quite verbose, especially if they're nested.
* **Nim:**   
  Syntax: `if condition: ifTrue else: ifFalse`

  + Advantage: Exactly like a normal `if` statement, so it's very natural.
  + Disadvantage: Not too bad, but it still does need the keywords `if` and `else` along with two colons.
> **Comments:**
> **username_23** (2023-05-16): Swift: parens optional, but braces required — `if a { b } else { c }`. This syntax had been used solely for statements for a while (opting for C’s `?:` for the expression), but was recently approved for expressions as well.  
> **username_16** (2023-05-16): The problem with `if condition ifTrue else ifFalse` is that `condition ifTrue` would, in many languages, be ambiguous, since e.g. `f(g)` is a valid expression but `f` and `(g)` are also valid expressions by themselves. Scala's solution using brackets is not the only option ─ Rust has `if condition {ifTrue} else {ifFalse}`, and F# has `if condition then ifTrue else ifFalse`.  
> **username_24** (2023-05-16): Another disadvantage of `?` and `:` is the ambiguity it creates with other common syntax, like trailing `?` operators  
> **username_25** (2023-05-16): An advantage for the Rust syntax (not sure if it applies to Swift as well) is that the ifTrue and ifFalse sections are complete blocks, so they can have their own scope for internal required calculations instead of being a single expression.  
> **username_7** (2023-05-17): The R syntax looks like a function call; does it short-circuit?  
> **username_26** (2023-05-17): Or don't have a ternary operator at all.  
> **username_27** (2023-05-17): I wouldn't consider it reasonable to criticise F# here, because there is no "normal if statement"  - because F# is expression based, that is the only if-else construct in the language. To call it verbose is to call a normal C style if statement verbose - while true, not quite reasonable when comparing it to a ?: ternary.  
> **username_23** (2023-05-17): @kouta-kun Swift distinguishes *`if` statements* (where the branches are full blocks) and *`if` expressions* (where each branch must be a single expression).  
> **username_19** (2023-05-17): @KarlKnechtel yes, it's both a function call and short-circuit: [Attempt This Online](https://ato.pxeger.com/run?1=m72waMGCpaUlaboW-zLTUnOKUzUMbYx0FAx0FAqKMvNKNJQyUnNy8pU0NSGKoGphegA)  
> **username_7** (2023-05-18): ... How can R call functions without fully evaluating their arguments first?  
> **username_19** (2023-05-18): @KarlKnechtel I'm not too sure, you'll have to ask an R expert for that.  
> **username_20** (2023-05-19): Scala 3 also permits if condition then ifTrue else ifFalse.  
> **username_9** (2023-07-01): @KarlKnechtel: It's called *lazy evaluation*. Most popular languages are *eager* by default, but there are some (e.g. Haskell) which are lazy by default. Some languages which are eager by default still allow lazy evaluation as an option (e.g. Scala). Even languages that don't, often have some builtin constructs which are lazy, for example, in many languages the boolean operators are lazy in their right operand. In R, specifically, [function arguments are *Promises*](https://cran.r-project.org/doc/manuals/r-devel/R-lang.html#Argument-evaluation). See https://langdev.stackexchange.com/a/275/854  
> **username_12** (2023-07-06): Nim: `if condition: ifTrue else: ifFalse`  
> **username_17** (2023-07-07): Excel also uses the R syntax  
> **username_21** (2023-07-13): Another downside of the Python system is that it has a confusing right-to-left evaluation order, differing from the rest of the language. Evaluation of the condition in the middle happens first, then evaluation of "ifTrue" may happen second.  
> **username_22** (2023-07-14): Python's `A if X else B` isn't non-intuitive (only) because of other languages, but also because it doesn't follow the structure of a regular `if`-statement _in Python itself_.  
---
### Answer by username_28 on 2023-05-16. Score: 13
There's always the Smalltalk postfix form.
result = condition ifTrue: [ ... ] ifFalse: [ ... ].

This has the benefit of not even being special syntax. It's just an ordinary application of the ifTrue:ifFalse: method on a Boolean object.
---
### Answer by username_11 on 2023-05-17. Score: 8
If your language supports lazy evaluation, if can be a regular function instead of a special form.
For example, in Mathematica, If is simply a built-in function that takes three arguments:
If[condition, t, f]

This function has the attribute HoldRest, which means that the arguments except the first one are not evaluated before the function is called.
Haskell also supports lazy evaluation, and you can define your own if function easily. I don't know why it chooses to use a special syntax for if instead of a function.
> **Comments:**
> **username_12** (2023-07-06): In Haskell, it's probably for readability: `if f x then g y else h z` is more readable than `if (f x) (g y) (h z)`.  
> **username_13** (2023-07-06): @xigoi Personally, I find the latter more readable.  
> **username_14** (2023-07-11): TSQL and VB implement it as a function this way, named `IIF` for `Inline If`  
> **username_13** (2023-07-15): There's a page on the Haskell wiki about this: https://wiki.haskell.org/If-then-else. (I agree that a plain function would be better.) Feel free to link to it to your answer.  
> **username_13** (2023-07-15): This can also be done in strict languages (see [my answer](https://langdev.stackexchange.com/a/2399/1368)).  
---
### Answer by username_1 on 2023-05-16. Score: 6
In an expression-oriented language such as Rust:
result = if condition { ifTrue } else { ifFalse }
---
### Answer by username_2 on 2023-07-06. Score: 6
One option is SQL's CASE WHEN foo THEN bar ELSE baz END. Advantages, in addition to the very clear syntax, are that it also can  be used as a binary operator CASE WHEN foo THEN bar END (defaulting to NULL) and as a superternary operator:
CASE
    WHEN foo THEN 1
    WHEN bar THEN 2
    WHEN baz THEN 3
    ELSE -1
END

The only disadvantage I can see is its verbosity, requiring 8 tokens in the ternary case instead of the 5 tokens of the less verbose languages.
> **Comments:**
> **username_3** (2023-07-06): This does not appear to answer the asked question  
> **username_2** (2023-07-07): @Starship-OnStrike How so? The first example does exactly the same thing as `foo ? bar : baz`  in C-like languages. A language designer could choose to limit the syntax to the ternary case or to support non-ternary usage as well.  
---
### Answer by username_4 on 2023-07-12. Score: 5
One interesting option, if your language has an Optional type, is to forgo having a traditional conditional expression structure entirely, but instead have operators designed for working with Optionals to achieve the same results conveniently:

c ? e would mean "if c evaluates to true, then the Optional containing the result of evaluating e, otherwise the empty Optional"
o : a would mean "if o is a non-empty Optional then its content, otherwise the result of evaluating a"

These two simple operations combine together to give the same behaviour as a C-style expression of the same form, and in most circumstances a relatively simple optimizer should be able to eliminate the creation of the Optional object, giving the same performance as a direct implementation.  They simplify parsing because you no longer need a special case for a ternary operator.
Note that because these operators have arguments that are expressions and they need to be able to control whether or not these expressions are evaluated, they either need to be language-level constructs (rather than simply defined using an operator overloading facility) or you need some other special faciity that allows arbitrarily short-circuiting evaluation (e.g. lazy evaluation or some kind of macro system that can operate on expressions as arguments)
Other syntaxes are, of course, also possible with similar semantics, e.g.:
Optional.ifTrue(c, e).orElse(a)

(which looks a bit like Java, but can't be implemented in Java for the reasons explained above)
> **Comments:**
> **username_5** (2024-09-18): Or you could make an `Optional` unit type your language’s Boolean, and `map` the `const` function to it..  
---
### Answer by username_6 on 2023-07-11. Score: 5
There's the Lisp style:
(IF condition then-expression [else-expression])

Lisp doesn't distinguish between statements and expressions, so this is both an if-statement and a ternary.
It's also a specialization of the more general COND:
(cond
    (condition1 body1...)
    (condition2 body2...)
    ...
    [(t else-body)]
)
---
### Answer by username_5 on 2023-07-10. Score: 5
There are three clauses, which can be permuted six ways:

if P then A else B
A if P else B
A else B if P
if P fails B otherwise A
B unless P then A
B except A if P

There are four slots in which to stick a piece of syntax (before, after, between the first and second, and between the second and third). In the examples above, I either put a keyword before each clause, or keywords between two clauses, but you can spell these however you like.
You could take a page from ML-family languages:
if p a b

But a stack-based language in RPN could be even more terse:
BAP?

Edit: This one actually does have implications for the semantics.  If there is no syntax separating the two branches explicitly, efficient short-circuiting is only possible if the runtime can figure out which commands are part of each branch of the tree statically, without evaluating both.  So, for example, we can’t have a Σ command that pops the number of terms to add together off the stack, then consumes that number of terms from the stack.  It would then be impossible to determine which tokens not to evaluate, without evaluating them.
Instead of keywords, you might use the offsides rule:
ifThenElse p
   A
   B

Although it’s handy to be able to write these as a one-liner too.  if you want these to be options, there should generally be some transformation between lists using indentation and those using separators.
> **Comments:**
> **username_7** (2023-07-11): If the expression requires exploiting the offside rule in a language that already ascribes meaning to that, it doesn't seem to have any real point - certainly it doesn't appear to have much of an advantage over actually using an `if` statement. This sort of thing also doesn't embed neatly as a subexpression of more complex expressions.  
> **username_7** (2023-07-11): In stack-based languages (and some others), on the other hand, the distinction between statements and expressions may well be moot. Still, I like this answer for the comprehensive overview of ways to construct the syntax.  
> **username_8** (2023-09-02): For stack-based languages, you have FORTH, which use `IF iftrue ELSE iffalse THEN`, with the condition taken from the stack before the IF.  The code in either the iftrue or iffalse will be executed and can do whatever it wants with the stack (consume values or push new ones), though the results can be difficult to understand if the two cases don't have the same delta stack depth.  
---
### Answer by username_9 on 2023-07-01. Score: 4
ruby
Ruby does not distinguish between statements and expressions – everything is an expression. Therefore, the traditional if/then/else can be used as an expression.
It is typically written as:
if condition
  consequence1
elsif other_condition
  consequence2
else
  consequence3
end

However, the line break to separate the condition from the consequence can also be written as a semicolon ; or as the keyword then, so the following are also both valid (and semantically equivalent):
if condition then consequence1 elsif other_condition then consequence2 else consequence3 end

if condition; consequence1 elsif other_condition; consequence2 else consequence3 end

Ruby also has the ternary conditional operator condition ? consequence1 : consequence3, but I personally consider it superfluous. The conditional operator's precedence in combination with Ruby allowing the leave out parentheses around argument lists in message sends also sometimes surprises programmers, whereas substituting the conditional expression into the same piece of code has the expected precedence.
---
### Answer by username_10 on 2023-05-19. Score: 4
Ada has conditional expressions if is one, case is another, they enclosed in parenthesis:
(if Casey.Sex = M then "Male" else "Female")

from the Ada 2022 RM.
---
### Answer by username_7 on 2023-07-07. Score: 4
An option I haven't seen is to preserve the order of C-like languages, but using keywords: `condition then ifTrue else ifFalse`. (This could also be described as "F# syntax, but without the leading `if`".)
---
### Answer by username_8 on 2023-09-02. Score: 3
Stack based langauges that directly use RPN tend to have quite different syntaxes for conditionals, built up from their underlying stack operations.

---

In [FORTH](https://en.wikipedia.org/wiki/Forth_%28programming_language%29), you have words that compile directly to (conditional) branches and branch targets:

* `IF`: pop stack and conditional branch forward if value popped is 0 (false)
* `ELSE`: unconditional forward branch + target of last unresolved IF branch
* `THEN`: target of last unresolved IF or ELSE branch

That gives you code that looks like

*cond* `IF` *iftrue* `ELSE` *iffalse* `THEN`

where *cond* is RPN code that leaves a boolean value on the stack, after which either the *iftrue* or *iffalse* code will run depending on whether that value was non-zero or zero.

---

In [Postscript](https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf), things are built around the `{`...`}` construct that compiles stored procedures -- any code in curly braces is compiled and a reference to the compiled code is pushed on the stack. That gives you code that looks like

*cond* `{`*iftrue*`}` `{`*iffalse*`}` `ifelse`

where `ifelse` just pops three things from the stack (condition and two stored procedure refs) and executes one of the stored procedures. If either of the latter is *not* a stored procedure, it will just be pushed back on the stack, so if you just want a value in either slot (rather than actual conditional execution), the braces are unneeded.
---
### Answer by username_13 on 2023-07-15. Score: 3
The conditional operator can be implemented without any special syntax or semantics beyond those of ordinary functions, even in strict languages.
In lambda calculus notation, let
id = λa.a
true = λa.λb.a
false = λa.λb.b
if = λp.λa.λb.p a b id

Then, for example:
if true (λx.then) (λx.else)
→ true (λx.then) (λx.else) id
→ (λx.then) id
→ then

Note that the branches are wrapped in thunks to prevent their contents from being evaluated eagerly.
---
### Answer by username_18 on 2023-05-16. Score: 3
VB.Net also features a fairly decent approach that is similar to R's approach (which was mentioned in [this answer](https://languagedesign.stackexchange.com/a/87/30)). There are two syntaxes:

* `result = IIf(expression, trueresult, falseresult)`
* `result = If(expression, trueresult, falseresult)`

The lattermost form was added later than the former, and obviously differs only by a letter, but has parity with the existing `If` syntax for ordinary if statements.
---
### Answer by username_15 on 2023-09-10. Score: 0
C# switch expression is almost directly analogous to SQL’s case expression.
Both can do exactly what a ternary expression does.
bool b = f(1);
var result = b switch  
{  
    true => "One",  
    false => "Two",
}; 

But are more powerful because they are not limited to just a single condition and so are easier to read with multiple conditions.
var result = i switch  
{  
    1 when y==2 => "One",  
    1 when y>4  => "Two",  
    3 => "Three",  
    44 => "Forty Four",  
}; 

```
> **Comments:**
> **username_16** (2023-09-10): This isn't a syntax option for a ternary/conditional expression, it's a different language construct.  
> **username_15** (2023-09-11): @kaya3: a ternary expression is just a switch expression which requires exactly 2 values, instead of 1 or more.  
> **username_17** (2023-09-11): @kaya3's point still stands  
> **username_15** (2023-09-11): @Seggan: look at my first example again, and tell me how it is not a ternary -- if the language description for that said "syntactic construct for returning one of two values based upon a boolean".  True, I am pointing out that it would be better to describe it as "syntactic construct for returning one of N values based upon the first matching condition", but it's a valid syntax for a ternary.  
> **username_15** (2023-09-11): @Seggan: if you include the requirement that true has to come before false, then there is nothing that can be done with a C-family ternary that can't be done with that syntax, and nothing can be done with that syntax that can't be done with a C-family ternary.  They are 100% matches.  
> **username_16** (2023-09-11): (1) As I said, it's a different language construct; the fact that you can use it as a substitute for a ternary expression does not make it a syntax option for a ternary expression; (2) If you are proposing this as a syntax option for a ternary expression, it's a pretty bad option. It's rather verbose since it spells out `true` and `false` as well as all the other punctuation; and I don't think any major style guide would recommend this, even in languages which lacked a proper ternary conditional operator.  
> **username_15** (2023-09-11): @kaya3: Not an answer. Also bad answer. Also violates style guide for unspecified language.  Gotcha  
---
