Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

condition execution using if or logic

Tags:

c++

when using objects I sometimes test for their existence e.g

if(object)
 object->Use();

could i just use

(object && object->Use());

and what differences are there, if any?

like image 469
Jet Avatar asked Nov 23 '25 09:11

Jet


2 Answers

They're the same assuming object->Use() returns something that's valid in a boolean context; if it returns void the compiler will complain that a void return isn't being ignored like it should be, and other return types that don't fit will give you something like no match for 'operator&&'

like image 156
Michael Mrozek Avatar answered Nov 24 '25 22:11

Michael Mrozek


One enormous difference is that the two function very differently if operator&& has been overloaded. Short circuit evaluation is only provided for the built in operators. In the case of an overloaded operator, both sides will be evaluated [in an unspecified order; operator&& also does not define a sequence point in this case], and the results passed to the actual function call.

If object and the return type of object->Use() are both primitive types, then you're okay. But if either are of class type, then it is possible object->Use() will be called even if object evaluates to false.

like image 30
Dennis Zickefoose Avatar answered Nov 24 '25 22:11

Dennis Zickefoose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!