Advertisement

Is if(Obj && Obj->Active) respectable code?

Started by October 11, 2002 07:12 AM
3 comments, last by Jiia 22 years, 1 month ago
The subject has all of the question. In one if statement, I'm asking if the pointer is not null, and also accessing data from the variable contained there. It looks dangerous, but it has always worked for me. Is this supported only by MSVC++ or by the C++ standard? In other words, will this always be translated to..
if(Obj)
   if(Obj->Active) 
? Do All compilers read left-to-right? Any suggestions on weather to use this? -Jiia [edited by - Jiia on October 11, 2002 8:18:11 AM]
c/c++ are guaranteed to perform lazy evaluation of all expressions.
This means that if the first term is enouth to determine the result of the logical operation, true on an OR and false on an AND, the second term won''t be evaluated.


Advertisement
Its called complete boolean evaluation. Some compilers do it which means all conditions in an If expression will be tested, which will make this code dangerous.

I had a look at the assembly code that MSVC generates and it seems safe. The conditions are tested from left to right and it will stop checking further as soon as one evaluates to false.

So to answer you:
Left-to-right
Wouldn''t recommend it, other compilers might do right-to-left and/or complete boolean evaluation.

<$1,000,000 signature goes here>
To answer your question: yes, it is respectable in C++, it is even a language feature (and should be used if it makes code more readable).

C++ guarantees lazy, left to right evaluation, if the || or && operators are used. So this statement is safe.

To quote Stroustrup:
The operators && and || will not evaluate their second argument unless doing so is necessary. For example,

if( p && l<p->count) ...

first tests that p is nonzero. It tests l<p->count only if p is nonzero.


/ Yann

[edited by - Yann L on October 11, 2002 10:24:46 AM]
Thanks for the replies. Especially with an answer I wanted to hear

There are a lot of lazy ways to do things in C++. I doubt all of them are respectful or easier to read. Here are a few I'll share with the unfortunate:

(Ptr1 = Ptr2)->FunctionToCall();
(IfThisIsTrue ? Ptr1 : Ptr2)->FunctionToCall();
FunctionToCall(IfThisIsTrue ? Data1 : Data2,IfThatIsTrue ? Ptr1 : Ptr2);
< template > nuf said, ha ha ha.

I've come up with crazier/pointless stuff, but I can't remember them now. There's no reason to smash everything onto one line, but I really enjoy it

[edited by - Jiia on October 11, 2002 11:50:51 AM]

This topic is closed to new replies.

Advertisement