detecting integer overflow

Bruce Karsh karsh at trifolium.esd.sgi.com
Sat Aug 25 15:00:25 AEST 1990


In article <67702 at sgi.sgi.com> karsh at trifolium.sgi.com (Bruce Karsh) writes:

>This should be

> 	if( (~a^b &  a^c) < 0) handle_overflow();

I can't get anything right today.  Bruce Holloway pointed out the precedence
problem.  It should be:

        if( ((~a^b) & (a^c)) < 0) handle_overflow();

because the precedence of & is higher than the precedence of ^.

Just to make sure this is right this time, a test case is attached below.

/* Test of software overflow handling. */
main()
{
	ofltst(0x80000000,0x80000000);
	ofltst(0x80000000,0x00000000);
	ofltst(0x80000000,0x7fffffff);
	ofltst(0x00000000,0x80000000);
	ofltst(0x00000000,0x00000000);
	ofltst(0x00000000,0x7fffffff);
	ofltst(0x7fffffff,0x80000000);
	ofltst(0x7fffffff,0x00000000);
	ofltst(0x7fffffff,0x7fffffff);
}
ofltst(a,b)
int a,b;
{
	int c;
	c=a+b;
        if( ((~a^b) & (a^c)) < 0) handle_overflow(a,b,c);
	else handle_nooverflow(a,b,c);
}
handle_overflow(a,b,c)
int a,b,c;
{
	printf("%11d = %11d + %-11d overflow\n",c,a,b);
}
handle_nooverflow(a,b,c)
int a,b,c;
{
	printf("%11d = %11d + %-11d no overflow\n",c,a,b);
}

			Bruce Karsh
			karsh at sgi.com



More information about the Comp.sys.sgi mailing list