I painstakingly wrote a macro over a course of years that does this: Macro which evaluates true if the expression (x+y) will result in arithmetic overflow. It also evaluates true if one of the operands is negative and the other is of a type that is too large to fit into a long long (because the result of the addition is not guaranteed in the C89 standard). Treat it as though it were defined something like this: bool ADD_WOULD_OVERFLOW({anyinttype} x, {anyinttype} y); I'm not 100% certain that I got all the edge cases right, but at least it passes my own test suite. One of the key insights to write this macro is this: while "x + y < x" is not guaranteed to be valid (if one of them is signed), "MAX_INT - x < y" is. #define ADD_WOULD_OVERFLOW_Styp(x, y, typ) ((((x) > 0) && ((y) > 0) && ((Z_MAX_typ(typ) - (x)) < (y))) || (((x) < 0) && ((y) < 0) && ((Z_MIN_typ(typ) - (x)) > (y))))
GCC and pointer overflows
Posted Apr 16, 2008 22:33 UTC (Wed) by gravious (guest, #7662) [Link]
How about? CLEAR_CARRY_FLAG // arch dep macro temp=x+y if (CARRY_FLAG_IS_SET) // arch dep macro naughty_naughty(); Surely an easy to find out if something WOULD_OVERFLOW is to perform the operation and check if it DID_OVERFLOW :)
Copyright © 2017, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds