Fandom

Programmer's Wiki

Ternary operator

406pages on
this wiki
Add New Page
Talk0 Share
16px-Pencil

The ternary operator is a replacement for the if statement. In some languages (e.g. C, awk), its syntax is as follows:

return(condition ? expression1 : expression2)

The ternary operator returns the value of whichever action it takes. In this way, it differs from the if statement, which does not (in most languages) return a value.

The example above is similar to:

 if condition
    return(expression1)
 else
    return(expression2)

Examples Edit

Curly bracket programming languages Edit

 variable = condition ? if_true : if_false;

Perl 6 Edit

The Perl6 ternary operator been changed to condition ?? true !! false . This is meant to be easier to remember, since ? is directly associated with true booleans, and ! is directly associated with false booleans since it is the not operator. Furthermore, this opens up the colon to all sorts of new uses.

variable = condition ?? true !! false;


Ruby Edit

In ruby the syntax is similar to Perl or C and is as follows:

return condition ? true : false

You can also use them in views like any other operator:

The answer is: <%= condition ? "true" : "false" %>.

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.