Home > Software engineering >  How to find absolute value in C?
How to find absolute value in C?

Time:04-13

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

CodePudding user response:

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.

CodePudding user response:

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];
}
  • Related