In the function, why is that there is (!) in the negative overflow while in posi
ID: 3754500 • Letter: I
Question
In the function, why is that there is (!) in the negative overflow while in positive over flow it doesnt?
Can someone explain the function please.
#include <stdio.h>
#include <limits.h>
/* Addition that saturates to TMin or TMax */
int saturating_add(int x, int y)
{
int sum = x + y;
int pos_overflow = !(x & INT_MIN) && !(y & INT_MIN) && (sum & INT_MIN);
int neg_overflow = (x & INT_MIN) && (y & INT_MIN) && !(sum & INT_MIN);
(!pos_overflow || (sum = INT_MAX)) && (!neg_overflow || (sum = INT_MIN));
return sum;
}
int main(int argc, char **argv)
{
printf("%d ", INT_MAX);
printf("%d ", INT_MIN);
printf("%d ", saturating_add(10, 10));
printf("%d ", saturating_add(INT_MAX, 10));
printf("%d ", saturating_add(INT_MAX, 0));
printf("%d ", saturating_add(INT_MIN, 10));
printf("%d ", saturating_add(INT_MIN, -2));
}
Explanation / Answer
It is only checking for overflow in negative not in positive . It's return 0 means false
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.