Search code examples
cabsolute-value

How to find absolute value in C?


I need to lighten the code, and then eliminate the underlying if that check if the subtraction are <0 and if the condition is true I multiply * -1 in order to have subtraction >0 (absolute value).

I wonder if there is a function or some operator able to perform the calculation directly in absolute value?

int i, j, N, max, s, s1;
s = v[i] - v[j];
s1 = i - j;
if (s1 < 0){
    s1 *= -1;
}
if (s < 0){
    s *= -1;
}

Solution

  • Absolute value

    To avoid int overflow of abs(v[i] - v[j]) and its undefined behavior (UB) , take advantage that the unsigned range is very commonly twice the int positive range and perform unsigned math.

    // int s;
    unsigned s;
    if (v[i] > v[j]) {
      s = 0u + v[i] - v[j];
    } else {
      s = 0u + v[j] - v[i];
    }