summaryrefslogtreecommitdiff
path: root/CSAPP/chap2/detect_overflow.c
diff options
context:
space:
mode:
Diffstat (limited to 'CSAPP/chap2/detect_overflow.c')
-rw-r--r--CSAPP/chap2/detect_overflow.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/CSAPP/chap2/detect_overflow.c b/CSAPP/chap2/detect_overflow.c
new file mode 100644
index 0000000..6badd11
--- /dev/null
+++ b/CSAPP/chap2/detect_overflow.c
@@ -0,0 +1,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;
+}
+