Both 'if' and 'else' executed

Thread Starter

AlbertHall

Joined Jun 4, 2014
12,347
In the code below, if BAUD_RATE1 and DESIRED_RATE are equal then both parts of the 'if' are executed. As, in those circumstances, both parts set BAUD_ERR1 to zero it does not cause a problem but it worries me that I don't understand why this code does that.

All variables are uint32_t, and the code is written for XC8

Code:
    if (BAUD_RATE1 >= DESIRED_RATE)
    {
        BAUD_ERR1 = (PP100K*(BAUD_RATE1-DESIRED_RATE)/DESIRED_RATE);
    }
    else
    {
        BAUD_ERR1 = (PP100K*(DESIRED_RATE-BAUD_RATE1)/DESIRED_RATE);
    }
 

BobTPH

Joined Jun 5, 2013
9,003
Borh the if and the else cannot ever be executed. What you might be seeing is a compiler optimization where both cases have some common code and the compiler jumps from one to the other after the different part has been done. This is a well known optimization called common tails.

Bob
 

Thread Starter

AlbertHall

Joined Jun 4, 2014
12,347
I think you are right. If I turn off optimisation I do not see the problem. However I have now changed the code to use abs() which avoids the 'if' altogether and is also smaller. It might be slower but I won't be changing the baud rate all that often so I can safely ignore that.
 

Analog Ground

Joined Apr 24, 2019
460
Borh the if and the else cannot ever be executed. What you might be seeing is a compiler optimization where both cases have some common code and the compiler jumps from one to the other after the different part has been done. This is a well known optimization called common tails.

Bob
Would this illustrate the sort of optimization you describe? In this case, it looks like a significant optimization for size.

if (BAUD_RATE1 >= DESIRED_RATE)
{
TEMP = (BAUD_RATE1-DESIRED_RATE);
}
else
{
TEMP = (DESIRED_RATE-BAUD_RATE1);
}
BAUD_ERR1 = (PP100K*(TEMP)/DESIRED_RATE);
 

BobTPH

Joined Jun 5, 2013
9,003
Yep, that is the idea, but the common code was probably considered part of the else, so, when stepping through it would go from the line in the if to the one in the else. I think that is what @AlbertHall was seeing.

Bob
 

402DF855

Joined Feb 9, 2013
271
I see similar behavior stepping through optimized C running on the ARM. If you look at the disassembled code the compiler is making use of condition codes on the ARM instructions, so the if and else can occupy the same emitted sequence.
 
Top