I came across the following line
hsb.s = max != 0 ? 255 * delta / max : 0;
What do the ?
and :
mean in this context?
I came across the following line
hsb.s = max != 0 ? 255 * delta / max : 0;
What do the ?
and :
mean in this context?
This is probably a bit clearer when written with brackets as follows:
What it does is evaluate the part in the first brackets. If the result is true then the part after the ? and before the : is returned. If it is false, then what follows the : is returned.
hsb.s = max != 0 ? 255 * delta / max : 0;
? is a ternary operator, it works like an if in conjunction with the :
!= means not equals
So, the long form of this line would be
Be careful with this. A -1 evaluates to true although -1 != true and -1 != false. Trust me, I've seen it happen.
so
-1 ? "true side" : "false side"
evaluates to "true side"
Properly parenthesized for clarity, it is
meaning return either
255*delta/max
if max != 00
if max == 0? :
isn't this the ternary operator?var x= expression ? true:false
It is called the Conditional Operator (which is a ternary operator).
It has the form of:
condition
?value-if-true
:value-if-false
Think of the
?
as "then" and:
as "else".Your code is equivalent to