tower120
tower120

Reputation: 5265

C++ if statement reordering

In my C++ (lets say this is gcc ) I do the following:

bool prevCurve;
bool curveInside;
bool prevCurveIn
if (!(prevCurve && curveInside == prevCurveIn)){
...
}

Will compiler optimize it like that:

bool prevCurve;
bool curveInside;
bool prevCurveIn
if (!prevCurve || curveInside != prevCurveIn){
...
}

Upvotes: 2

Views: 626

Answers (2)

László Papp
László Papp

Reputation: 53225

This is entirely up to your compiler and the code around, but this would not be an optimization after all considering the most common instruction sets out there.

The reason is that you have three operations to be executed either way:

  • one evaluation, either variable or negated variable
  • negation
  • OR/AND

The order might be different, but these points have to be executed. I am not aware of any instruction set where one can be optimized over the other.

As written in the comment, the compiler could even optimize out varibles if they have constant values, what optimization options you use for gcc, which version of gcc, which architecture, different platforms, etc.

The best way would be to compare the assembler outputs that you can generate with:

gcc -S main.cpp

Upvotes: 2

david.pfx
david.pfx

Reputation: 10863

No. When evaluating this expression:

if (!(prevCurve && curveInside == prevCurveIn)){

The standard requires that prevCurve be evaluated fully including any side-effects before the evaluation of the remainder of the expression. The operator '&&' introduces a sequence point. In the case of the equivalent:

if (!prevCurve || curveInside != prevCurveIn){

The operator || also introduces a sequence point.

It is theoretically possible that a compiler might generate identical code in the two cases but even if it does this is not optimisation. Leaving aside the possibility of optimisation based on other considerations, the code in each case will execute a similar sequence of instructions with exactly the same result. The standard requires that this be so.

Upvotes: 2

Related Questions