[comp.lang.c++] MININT problem with C++ streams

edward@runxtsa.runx.oz.au (Edward Birch) (07/12/90)

MININT is not printed out correctly by some Glockenspiel and AT&T
C++ compilers.

The below program produced the following output:

	assuming 2's complement arithmatic &
	     sizeof(long) = 4 & 8 bits per byte

	then using `C' we get MININT =  80000000 or -2147483648
	and using  C++ we get         = 80000000 or -(

------------------------------------------------------------------------

#include	<stream.h>
main()
{
	long	x = 0x80000000; /* minint, -2147483648 */

	printf("assuming 2's complement arithmatic &\n");
	printf("     sizeof(long) = 4 & 8 bits per byte\n");
	printf("\n");
	printf("then using `C' we get MININT =  %08lx or %ld\n", x, x);

	cout << "and using  C++ we get         = " << hex(x, 8);
	cout << " or " << x << "\n";

	return 0;		// exit(0);
}

------------------------------------------------------------------------

I think the bug is caused by an assumption in the C++ library
going something like:

	if (v < 0) {
		emit_char('-');
		v = -v;		// clearly wrong when v = MININT with
				// (2's complement arithmatic)
	}

------------------------------------------------------------------------

Edward Birch

                                        Phone:   (02) 958-2119

UUCP:   seismo!munnari!runx.oz!edward   ACSnet:  edward@runx.oz
ARPA:   edward%runx.oz@seismo.css.gov   CSNET:   edward@runx.oz

ggs@ulysses.att.com (Griff Smith) (07/13/90)

In article <1959@runxtsa.runx.oz.au>, edward@runxtsa.runx.oz.au (Edward Birch) writes:
| MININT is not printed out correctly by some Glockenspiel and AT&T C++ compilers.

This may have been a problem with the AT&T 1.2 release, but it works on
my system with the 2.1 release.

| I think the bug is caused by an assumption in the C++ library
| going something like:
| 
| 	if (v < 0) {
| 		emit_char('-');
| 		v = -v;		// clearly wrong when v = MININT with
| 				// (2's complement arithmatic)
| 	}
| 
| Edward Birch
|                                         Phone:   (02) 958-2119
| 
| UUCP:   seismo!munnari!runx.oz!edward   ACSnet:  edward@runx.oz
| ARPA:   edward%runx.oz@seismo.css.gov   CSNET:   edward@runx.oz

Actually, it isn't wrong on a 2's complement machine if the `v = -v'
operation doesn't cause an overflow trap.  The trick is to cast the
resulting number to unsigned and then do the conversion.
-- 
Griff Smith	AT&T (Bell Laboratories), Murray Hill
Phone:		1-201-582-7736
UUCP:		{most AT&T sites}!ulysses!ggs
Internet:	ggs@ulysses.att.com