Re: Exceeding limits during arithmetic



Mike Aubury wrote:

Is there any standard (or even non-standard) way to detect limit
overflow in arithmetic in C ?

eg.
/* assuming 4 byte ints.. */
int a=2147483647;
int b=2147483647;
int c;

c=a*b;

if (INT_MAX / b < a) overflow();
else c = a * b;

and #include <limits.h>. Diddle to handle -ve input values.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
<http://kadaitcha.cx/vista/dogsbreakfast/index.html>
cbfalconer at maineline dot net



--
Posted via a free Usenet account from http://www.teranews.com

.



Relevant Pages

  • Re: Portability: Harmony between PC and microcontroller
    ... int is the natural integer type for the system. ... You are, perhaps unintentionally, paraphrasing the standard in a way ... One of the things that you might not realize is that the C programming ... In the real world, most embedded systems have more complex jobs to do, ...
    (comp.lang.c)
  • Re: Plauger, size_t and ptrdiff_t
    ... Plauger's "The Standard C Library," where he states "... ... This language would not rule out one being int ... we explicitly decided to allow some pointer differences to be ... BTW, even when you do get a ptrdiff_t overflow, on a ...
    (comp.lang.c)
  • Re: progrm to find a substring in a string
    ... Use either int mainor int main(int argc, ... char **argv). ... CBFalconer as a non-standard but more robust variant. ... This function can be replaced by the standard strstr() function. ...
    (comp.lang.c)
  • Re: Bit-fields and integral promotion
    ... > un/signed type knowledge. ... unsigned char, the int-sized object must be treated as signed. ... Admittedly it is unfortunate that the standard does not specifically ... int but an 8-bit unsigned bit field promoted to an unsigned int. ...
    (comp.lang.c)
  • Re: call of variadic function
    ... arguments that should be passed to this function are of type int. ... You call foo with more arguments than are ... which is the standard way to access arguments of a variadic function ... Here the else clause of my sentence specifies one of the numerous non- ...
    (comp.lang.c)