Home of the AlmostImplementedException

The conditional operator (?:)

Most of you will already know this operator, but i think its useful to write something about it anyway. Maybe someone who doesn’t know it, come across it here.

In short the conditional operator checks if the given condition is true or false and returns the first or the second value accordingly. And here is a little example:

This short code checks if a is larger then b and if it is set the variable i to the value of a. Otherwise it is set to the value of b. The conditional operator is just a short way to write if else statements and the code above could also be:

Its also possible to write more complex statements, but its not recommended because of the readability of the code. But anyway here is a more complexe example:

Since this operator is right-associative (in opposite to PHP, where it is left associative), this code is interpreted as a > b ? a : (b > c ? b : c). The part in parenthesis is only execute if the first condition is false (a is not larger then b).
This translates into:

And for all the pour souls that try the same thing with PHP, read this to see how it works with left-associative

Share :

, ,

Leave a Reply