From d98f46ce647846b0aa30b2e16a30fd4e152a1bf5 Mon Sep 17 00:00:00 2001 From: Carlos Maiolino Date: Thu, 10 Jul 2025 22:55:07 +0200 Subject: Add new code Signed-off-by: Carlos Maiolino --- CSAPP/chap2/detect_overflow.c | 54 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 CSAPP/chap2/detect_overflow.c (limited to 'CSAPP/chap2/detect_overflow.c') 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 +#include +#include +#include + +/* + * 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; +} + -- cgit v1.2.3