How to find absolute value in C?

402 Views Asked by At

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;
}
2

There are 2 best solutions below

0
On BEST ANSWER

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];
}
0
On

As the comments say:

s = abs(x - y)

The manpage for abs (and also labs, llabs): https://linux.die.net/man/3/abs

It looks like you're doing this in a for loop of some sort (i,j are hopefully loop indices, otherwise you need to name your variables more descriptively). In that case, you should be able to architect it such that j is never greater than i for a performance increase.