blob: 6badd11c64c0620ab75d49911c90587bfb92a1f4 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <limits.h>
/*
* Determine whether arguments can be added without overflow
* Two's complement
*
* Returns 1 if arguments can be added without overflow
* 0 otherwise
*/
int tadd_ok(int x, int y)
{
// if ((x > 0 && y > 0) && (x + y) < 0 ||
// (x < 0 && y < 0) && (x + y) > 0)
// return 0;
// else if ((x < 0 && y < 0) && (x + y) > 0)
// return 0;
// else
// return 1;
/* Negative overflow can also be 0 */
return !(((x > 0 && y > 0) && (x + y) < 0) ||
((x < 0 && y < 0) && (x + y) >= 0));
}
int uadd_ok(unsigned x, unsigned y)
{
return ((x + y) >= x);
//return ((x + y) < x) ? 0 : 1;
}
int main(void)
{
unsigned a = 5;
unsigned b = 0;
int X = INT_MIN;
int Y = INT_MIN;
int ret;
ret = uadd_ok(a, b);
printf("SUM: %u\n", a + b);
printf("Return is: %d\n", ret);
ret = tadd_ok(X, Y);
printf("Signed values\n");
printf("SUM: %d\n", X + Y);
printf("Return is: %d\n", ret);
return 0;
}
|