I was wondering if the && operator works in a cascading manor. Compare the following implementations of a rectangle collision check.
inline bool RectInRect(RECT one,RECT two){
if(one.left < two.right)
if(one.right > two.left)
if(one.top < two.bottom)
if(one.bottom > two.top)
return true;
return false;
}
inline bool RectInRect(RECT one,RECT two){
return (one.left < two.right && one.right > two.left &&
one.top < two.bottom && one.bottom > two.top);
}
Are these both the same or will the top one operate faster?
Yes, the second version essentially boils down to the first. The relevant property of the operator is that it’s short-circuited: the second operand is only evaluated if necessary, that is, if the first operand evaluates to
true. Otherwise, the whole expression will always evaluate tofalseso there’s no need to look at the second operand.This behaviour is guaranteed and is analogous, but the other way round, for
||/or.