I have a program that I am trying to understand but there is an abbreviated code or codes that i don’t understand.
the code is
double xDistance = x1 - x2 >= 0 ? x1 - x2 : x2 - x1;
double yDistance = y1 - y2 >= 0 ? y1 - y2 : y2 - y1;
i read in programming books that ?: is an abbreviated form of if…then but where do i put these words in because everytime i insert or replace some code I get a syntax error.
Also are there more than one way to write the following line of code
(xDistance <= (w1 + w2) / 2 && yDistance <= (h1 + h2) / 2)
preferably replacing the && operator
thanks in advance for any assistance given.
The conditional operator
? :is shorthand forif-elseand works as so:Therefore
equates to:
The second line:
is the same thing, equates to:
Which is storing the absolute values (ie. distance rather than displacement) in
xDistanceandyDistance. Can also be replaced withMath.abs(x1 - x2), etc.And why do you want to replace the
&&operator in the following?If you really had to you could have (assuming this statement belongs in an
ifstatement):EDIT: As mentioned by David in the comments,
&&is simply a logical AND. ie. forX && Y, the expression is TRUE iff bothXis TRUE andYis TRUE.Because of this you can take advantage of short-circuiting, where if the first condition (
X) is FALSE, then there is no point in the program evaluating the second (Y) since the expression can never be TRUE.