Could someone tell me why I can't use a Ternary operator in a mathematical function?
Here's an example:
<cfset test = 1>
<cfdump var="#structKeyExists(Variables, 'test') ? 1 : 0 + 20#">
I would expect the result of this to be 21
, however the result actually comes out as 1
.
I discovered this on CF10, and when I tested it on Railo it came out the same so I'm wondering: is this a bug or is there a reason I'm not supposed to be able to use a Ternary operator in this context?
The false statement of your ternary doesn't end at the 0, it ends at the end of the line of code. When the check is false, the ternary will return statement right of the :
, in your example 0 + 20
.
As Beginner has recommended, using brackets will allow you to end the ternary earlier, and continue to manipulate the result. <cfdump var="#(structKeyExists(Variables, 'test') ? 1 : 0) + 20#">
will give you 21 or 20 as expcted.