2.4.4. Saturation in C

To perform efficient saturation in C on the C28x, use the ternary ?: operator.

Using if results in the following code with -O3:

Table 2.7 Saturation with if - inefficient

C Source

Generated Assembly

int saturate(int sum, int max, int min)
{
    if( sum > max )
        sum = max;
    if( sum < min )
        sum = min;

    return sum;
}
||saturate||:
        MOVZ      AR6,AL
        MOV       AL,AR4
        CMP       AH,AR6
        MOV       AR6,AH,LT
        CMP       AL,AR6
        MOV       AR6,AL,GT
        MOV       AL,AR6
        LRETR

Using ?: generates the much more efficient MAX/MIN instructions:

Table 2.8 Saturation with ?: - efficient

C Source

Generated Assembly

int saturate_opt(int sum, int max, int min)
{
    sum = (sum > max) ? max : sum;
    sum = (sum < min) ? min : sum;

    return sum;
}
||saturate_opt||:
        MIN       AL,AH
        MAX       AL,AR4
        LRETR