We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Ternary expressions behaving unexpectedly
Page Index Toggle Pages: 1
Ternary expressions behaving unexpectedly (Read 617 times)
Ternary expressions behaving unexpectedly
Dec 5th, 2005, 8:32pm
 
The following expression works perfectly in Processing 0097

return (vX) ? eX++ : eX--;

However, this next expression fails with Syntax error: <= expected instead of this token.

return (vX) ? eX += o_dx : eX -= o_dx;

This is somewhat confusing because <= has no place in that expression. Can someone please help? Sad
Re: Ternary expressions behaving unexpectedly
Reply #1 - Dec 5th, 2005, 9:37pm
 
I'm not sure what you're trying to do there. Putting a test in a return statement is likely to mess up the precedence of how things are run, you may be thinking "if vX, return either eX+=o_dx or eX-=o_dx" (which in itself is nasty, since youre relying on the (a+=b) returning a result equal to a+b), but the compiler might see "if (return vX) then add o_dx to eX or subtract o_dx from eX" which doesn't really make sense, but is possible, depending on the precedence used in the interpreter/compiler.

?: is one of those operators that has very limited good use, and I don't think your example is it.

If however you're still wanting to use it, I recommend adding lots of brackets to avoid any ambiguity in what you mean, e.g.:
return ( (vX) ? (ex+=o_dx) : (ex-=o_dx) );

Personally I'd do:
if(vX)
 ex+=o_dx;
else
 ex-=o_dx;
return ex;

Re: Ternary expressions behaving unexpectedly
Reply #2 - Dec 5th, 2005, 9:39pm
 
you might be able to get it to work via:

return (vX) ? (eX += o_dx) : (eX -= o_dx);

but i would strongly discourage mixing a += and -= with a ? statement. using ? and : to evaluate is considered bad style enough as it is without also being mixed with more statements on top. i think the ? and : are useful, but the above example is gonna be difficult to read.

(assuming you actually want += and not just +)
Page Index Toggle Pages: 1