glenstorey
glenstorey

Reputation: 5154

Is it safe to have an invalid operation in the second half of && in an if statement?

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.

Upvotes: 4

Views: 107

Answers (3)

loki11
loki11

Reputation: 374

Yes, for built in types (like booleans). This behavior is known as short circuiting. This occurs because && is actually a function associated with the first statement in the expression, though it special syntax due its status as an operator as well. Inside this function, there will generally be a check for nullity as well as if the expression is false. In the case of the && operator, if the boolean is false, this is sufficient grounds to cease evaluation of the logical expression and will result in saved evaluation time.

Upvotes: 2

AnT stands with Russia
AnT stands with Russia

Reputation: 320681

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.

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258628

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 is false.

Upvotes: 8

Related Questions