diff options
| author | Carlos Maiolino <[email protected]> | 2025-07-10 22:55:07 +0200 |
|---|---|---|
| committer | Carlos Maiolino <[email protected]> | 2025-07-10 22:56:55 +0200 |
| commit | d98f46ce647846b0aa30b2e16a30fd4e152a1bf5 (patch) | |
| tree | 267474fcc77cf20b428f6f4c7f768ca09f4cfe0e /CSAPP/chap2/detect_overflow.c | |
| parent | 869e68986aa8f69af6e7842260a68d1e5c6f796f (diff) | |
Add new code
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'CSAPP/chap2/detect_overflow.c')
| -rw-r--r-- | CSAPP/chap2/detect_overflow.c | 54 |
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; +} + |
