[prog] Re: weird <? operator

Meredydd meredydd at everybuddy.com
Sat May 31 13:03:24 EST 2003


On Saturday 31 May 2003 12:44, Rachel McConnell wrote:
> similar to your example, although I've boldly switched from > to < in
> mine.  Note that in Java (and probably elsewhere), the order of
> operations requires the ternary operator to be evaluated prior to the
> assignment operator, so if you wanted to test equality you'd need a set
> of parentheses, like so:
>
>    ( varX = 100 ) ? varX++ : varX-- ;
Actually, as you go on to explain, this won't test for equality at all. It 
will assign "100" to the variable varX, and then use that as a test.

In C, this will work (zero is defined as "false", anything else as "true"), 
and the effect will be the same as "varX = 101;"
	
Java, however, has the very sensible feature of having a "boolean" data type, 
distinct from "int". As a result, your code there will result in an error 
("Type mismatch: expecting boolean, got int at line XYZ", or something 
similar). This is useful, although it's a pain in the butt when I change 
languages and try to write "while(1)" in Java ("while" takes a boolean only), 
or "while(true)" in C ("no such identifier").

To avoid confusion, I always explicitly bracket my code using "?:" - for 
example:

(x>100)?(x--):(x++);

That way there can be no ambiguity, and I don't end up chasing subtle 
order-of-operation bugs around the place :)


Meredydd


More information about the Programming mailing list