Is this safe:
if(sprite->numberOfSides !=0 && sprite->value%sprite->numberOfSides!=0)
if sprite->numberOfSides can == 0?
The reason I ask, is if I frame the if statement like this:
if(sprite->value%sprite->numberOfSides!=0 && sprite->numberOfSides !=0)
I get an exception (because you can't n%0). Reversing it to the former statement works fine, but I don't want trouble down the road when compiling for different devices.
Yes it's safe. Short-circuiting is guaranteed by the standard.
This means that if the first part of an and (&&
) expression evaluates to false
, it's guaranteed that the second part won't be evaluated.
From C++03 - 5.14/1
The
&&
operator groups left-to-right. [...] the second operand is not evaluated if the first operand isfalse
.
It is safe as long as you are talking about the built-in &&
operator. As other answers already noted, the evaluation of the built-in operator is short-circuited: the left operand is always evaluated first, and if it evaluates to false
, the right operand is not even touched.
However, when you are dealing with overloaded operator &&
, it behaves as any other overloaded binary operator, meaning that both operands are evaluated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With