Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 234
glenstorey Avatar asked Dec 08 '22 23:12

glenstorey


2 Answers

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.

like image 135
Luchian Grigore Avatar answered Dec 22 '22 01:12

Luchian Grigore


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.

like image 31
AnT Avatar answered Dec 22 '22 00:12

AnT