Proper Parentheses Placement In Ternary Statements

Consider the following code:

a = b = c = 1000000;
r = (a > 10000) ? a/1000 : a & "/" & (b > 10000) ? b/1000 : b & "/" & (c > 10000) ? c/1000 : c;

(if you think the first line is odd – see Chaining ColdFusion Assignment Operators)

My thought was r would return “1000/1000/1000” — however it actually returned “1000”. Where did I go wrong?

Now if I change a,b,c to 1000 it would blow up to a “cannot convert the value “1000/NO” to a boolean” error.

So what’s going on? The third argument of the statement becomes another ternary statement but can not convert the evaluated “1000/NO” to a Boolean – thus blowing up. If a,b,c = 1000000 then the operation never gets to the third argument and returns only “1000” never considering the ampersand in its logic.

So correct code would be:

a = b = c = 1000000;
r = (a > 10000 ? a/1000 : a) & "/" & (b > 10000 ? b/1000 : b) & "/" & (c > 10000 ? c/1000 : c);

Or depending upon your preference:

a = b = c = 1000000;
r = ((a > 10000) ? a/1000 : a) & "/" & (b > 10000) ? b/1000 : b) & "/" & (c > 10000) ? c/1000 : c));

Now there are three seperate ternary statements concatenated together with a slash between them.