?
Solved

optimizing if() in VS 2005 c++

Posted on 2007-07-20
19
Medium Priority
?
253 Views
Last Modified: 2013-11-26
Hi,

I'd like to know whether VS 2005 (native c++ code, not .NET) automatically optimzes if() statements with multiple conditions to enter the block of code as soon as one of the conditions is true.

For example,

    if( isYummy() || reallyHungry() || haveGunPointedAtMe() ) {
                 eat();
     }

if the three functions all return a bool, then how will the compiler handle the entire if(). Will it execute isYummy() first?  What is the guaranteed order?  If it finds one of the functions to be true, will it call the others?  

What I _want_ is for the first function to be called and if not true, then the second to be called, and if not true, the third to be called.  My goal is to increase performance by not calling the last two functions if its not necessary.

Thanks

kevin
 
0
Comment
Question by:highqllc
  • 6
  • 4
  • 4
  • +4
19 Comments
 

Author Comment

by:highqllc
ID: 19530799
I should emphasize that it is absolutely critical that isYummy() called while I don't care of the other functions are called.
0
 
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 150 total points
ID: 19530844
It uses short-cut logic:

With 'or' operators, if the first condition is true, then the resulting expression will be true, so no further processing is required.

With 'and' operators, if the first condition is false, then the resulting expression will be false, so no further processing is required.

Evaluation for complex expressions can be more difficult to understand, but operate on the basic Boolean logic principals.

Bob
0
 

Author Comment

by:highqllc
ID: 19530858
But it is guaranteed that isYummy() is _always_ called in my example?  I.e., there's no strange conditions whereby the compiler would decide to switch up the order that the individual logic statements are evaluated?
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
LVL 22

Assisted Solution

by:Bill-Hanson
Bill-Hanson earned 75 total points
ID: 19531116
Yes, isYummy will always be called.  What's more, if isYummy always returns true, the other two will never be called.  If you're still in doubt, just nest your ifs.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19531132
>> But it is guaranteed that isYummy() is _always_ called in my example?

Yes, but the others aren't guaranteed to be called.

The order in which they are called is the order in which you typed them.

So, conceptually, it's similar to :

     if(isYummy()) {
                 eat();
     }
     else if (reallyHungry()) {
                 eat();
     }
     else if (haveGunPointedAtMe()) {
                 eat();
     }
0
 
LVL 22

Assisted Solution

by:grg99
grg99 earned 75 total points
ID: 19531165
The language guarantees the order of evaluation,  but IMHO if it's that critical, just write clearer code using three ifs() so there's no doubt in anybody's mind what will get executed and when.

0
 
LVL 3

Assisted Solution

by:asood314
asood314 earned 150 total points
ID: 19533747
If you ever have a situation like this where you need all three functions to be called, use a single | or &.  For instance, if you wrote:

if(isYummy() | reallyHungry() | haveGunPointedAtMe())
{
    eat;
}

then short-cut logic is no longer used, and all 3 functions are called.
0
 
LVL 22

Expert Comment

by:Bill-Hanson
ID: 19533973
Nice!  I didn't know that.
0
 
LVL 1

Expert Comment

by:sleep_pilot
ID: 19534223
IMHO, if you REALLY want isYummy() to be called, instead of doing what you have, have it done this way:

bool myIsYummy = isYummy();
if( myIsYummy  || reallyHungry() || haveGunPointedAtMe() ) {
                 eat();
     }

Then you don't need to unroll the if() into 3 if-elses.
0
 
LVL 1

Assisted Solution

by:sleep_pilot
sleep_pilot earned 75 total points
ID: 19534239
Just an aside, I would add a comment for the myIsYummy line to state that isYummy() must be called, (I assume, because there is side effect in that function that must be executed) so whoever look at the code later won't change it.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19534275
sleep_pilot : the first function will be called in any case, so there's no need to use your technique. However, it might be handy if you need the other two functions to be called in all cases :

    bool myReallyHungry = reallyHungry();
    bool myHaveGunPointedAtMe = haveGunPointedAtMe();
    if( isYummy()  || myReallyHungry || myHaveGunPointedAtMe ) {
                 eat();
     }
0
 
LVL 1

Expert Comment

by:sleep_pilot
ID: 19534340
Infinity08: in the current version of compiler, that's true.  However, at high opt. the compiler may decided to move calls around.  (Not that I have an example of compiler that does that.)

I think, ultimately, it's best to not depends on side effect of functions.  For better software design, the side effect should be factored out to another function that will be called all the time.

YummySideEffect();
if (isYummy() || reallyHungry() || haveGunPointedAtMe()) {
  eat();
}

Done this way, the isYummy() code can be mark as const only, so this gives advanced compiler more freedom to inline the call (and less surprise for the developer 1yr down the road.)
0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 225 total points
ID: 19534423
>> Infinity08: in the current version of compiler, that's true.  However, at high opt. the compiler may decided to move calls around.  (Not that I have an example of compiler that does that.)

Actually, no. The standard is very clear about that :

        "The || operator groups left-to-right. The operands are both implicitly converted to bool (4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.
        The result is a bool. All side effects of the first expression except for destruction of temporaries (12.2)
happen before the second expression is evaluated."


>> I think, ultimately, it's best to not depends on side effect of functions.  For better software design, the side effect should be factored out to another function that will be called all the time.

That's still good advice however. Not because it won't work otherwise, but because the code is clearer, and will cause less confusion for those not knowing the details of the C++ language.
0
 
LVL 1

Expert Comment

by:sleep_pilot
ID: 19534992
Infinity08: Yes, you are right. I stand corrected.  It's in section 5.15 Logical OR operator [expr.log.or] of the C++ Standard.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19537497
May I ask why you gave a B grade ? Was something still not clear ? If so, then please tell us what, and we'll be happy to answer your further questions !
0
 

Author Comment

by:highqllc
ID: 19537537
Hi,

I didn't think about the grade at all, honestly. Divying out points seems important to me, but it's not clear what the "grade" is used for.  Is it important?  I just hit "good" by default because most advice I get on here is just that, quite good.  ...Seems like A should be reserved for "outside the bell curve" answers that really blow one's socks off.  I can see your perspective too: if the question was answered adequately, an A should be given.    Well... nah... that's lame...    It's like in back in college, most professors would set the curve a bit high, at maybe a B+, elevating all grades a bit, making students feel good and proving their success in teaching the material.  Buth the hardliners would set the curve at a B- or C+, and literally force half of the students to get C's, D's, and F's even if they all knew the material quite well.   An "A" was exceptional.  I liked those professors. They gave an "A" real value.

In any case,  I will take the grade more seriously in the future if it really matters to the experts.

kevin
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19537555
>> but it's not clear what the "grade" is used for.

This should explain it :

http://www.experts-exchange.com/help.jsp#hi73


>> In any case,  I will take the grade more seriously in the future if it really matters to the experts.

Well - it matters to know whether the answer you gave was correct and complete. As explained in the link above, a B grade usually means that the answer was incomplete - meaning that some work from your side was required to fill in the blanks. It also means that we as experts didn't give our 100% when answering your question, and that we could have done better.

That's all there is to it : I strive to give the best help possible, and a B grade usually indicates that there was something missing. If so, I'd like to learn from it, and try to do better by giving the missing information now and in the future.

I hope that makes sense to you ?
0
 

Author Comment

by:highqllc
ID: 19537562
Cool. That link puts the grading system on a fairly objective level that I can try to be congruent with in the future. If it's possible to change grades after-the-fact, I can do that with this question.

Kevin
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19537570
No need, Kevin :) If I know that you are happy with the answer, that's enough for me. But thanks for the offer.

Just fyi : should you in the future need to change or do something that you can't do yourself, you can post a 0-point question for that in Community Support :

http://www.experts-exchange.com/Community_Support/General/
0

Featured Post

2018 Annual Membership Survey

Here at Experts Exchange, we strive to give members the best experience. Help us improve the site by taking this survey today! (Bonus: Be entered to win a great tech prize for participating!)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

601 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question