summaryrefslogtreecommitdiff
path: root/2/3_int_arith/230.c
diff options
context:
space:
mode:
authorMike Vink <mike@pionative.com>2024-05-22 08:49:29 +0200
committerMike Vink <mike@pionative.com>2024-05-22 08:49:29 +0200
commit51169f5f9ab178a4ddfe9dac461405a71c9c0f94 (patch)
tree0b6bb0c6c31ee27361b28e2c5993f362c1cc95e2 /2/3_int_arith/230.c
parent77f19e4a89d8dec97930c5e237139734c5fb3365 (diff)
organise
Diffstat (limited to '2/3_int_arith/230.c')
-rw-r--r--2/3_int_arith/230.c25
1 files changed, 25 insertions, 0 deletions
diff --git a/2/3_int_arith/230.c b/2/3_int_arith/230.c
new file mode 100644
index 0000000..8bba282
--- /dev/null
+++ b/2/3_int_arith/230.c
@@ -0,0 +1,25 @@
+#include <limits.h>
+#include <stdio.h>
+
+int tadd_ok(int x, int y) {
+ int positive_overflow = x > 0 && y > 0 && x + y < 0;
+ int negative_overflow = x < 0 && y < 0 && x + y >= 0;
+ return !positive_overflow && !negative_overflow;
+}
+
+int tadd_buggy(int x, int y) {
+ int sum = x+y;
+ printf("sum: %d, sum-x: %d, sum-y: %d", sum, sum-x, sum-y);
+ return (sum-x == y) && (sum-y == x);
+}
+
+/* buggy */
+int tsub_ok(int x, int y) {
+ return tadd_ok(x, -y);
+}
+
+void main() {
+ printf("INT_MIN: %d, %d\n", -(INT_MIN), INT_MIN);
+ printf("result: %d\n", tadd_ok(10, 100));
+ printf("result2: %d", tadd_buggy(INT_MAX, 1)); // The sum is a very negative number, when we take the difference with it's parts it just does a negative overflow to get the original parts back.
+}