SUMMARY: Apparent compiler problem using large integer constants

Wes Pfarner (wrpfarn@csua35.sandia.gov)
Wed, 30 Apr 1997 12:32:39 -0600

Sorry to be so long with the summary, but things keep happening around here.
Including my email address turning bogus on the day I sent the message. I'm
sorry that those of you who replied couldn't get through our DNS minefield.

I did get a couple of replies and an apparent solution. Thanks to Torsten
Metzner and Chris Conway for the help. Their answers are appended. Both
answers are correct, but we actually used Chris's suggestion to use hex
numbers in boundary cases.

Even though the subject was a bit off-track, the answers are appreciated and
they made things a bit better here.

Thanks,

Wes

Wes Pfarner Sandia National Labs Dept. 6532 MS 1138
PO Box 5800, Albuquerque, New Mexico 87185-0655
wrpfarn@sandia.gov 505-844-0684 FAX 505-284-3850

---------The Original Problem Statement--------------

If you C++ compile and execute the following program,

extern "C" { int printf(...) ; }

main()
{
int low = -2147483648 ;
int high = 2147483647 ;

int test = 90 ;

if ((test < -2147483648) || (test > 2147483647))
printf("Error1\n") ;

if ((test < low) || (test > high))
printf("Error2\n") ;

printf("low = %d high = %d\n",low,high);
}

you should get the following result:

Error1
low = -2147483648 high = 2147483647

This implies that the compiler is not correctly compiling the numbers
-2147483648 and 2147483647 when they are plugged directly into the code,
but it works fine if variables are assigned these values and used for
comparison. Is this a plot by compiler writers to prevent programmers
from using constants directly in their code ?

Any ideas ?

-----------Torsten Metzner's Reply -------------------

I don't think so {;-)

If you use a clean programming style everything works.
Use:
INT_MIN instead of -2147483648 and
INT_MAX instead of 2147483647 // That's not necessary
You must include the limits.h file for this.

and everything is fine. Why ?

INT_MIN is (- 2147483647 -1) and that's different from -2147483648 ( for
a compiler, if it's interpreted as (-1) * 2147483648, because 2147483648
is too big for an int ).

------------Chris Conway's Reply -------------------

I know that some compilers have been reported to have a problem with
using constants set to the lowest possible negative number; apparently
these compilers read in the constant as a positive integer, and then
negate it; so, your "low" constant would be set to - (2147483648) instead
of simply -2147483648. The 2147483648 overflows, of course, resulting
in the constant not being what you expect it to be. Try doing it using
hex numbers instead (0x7fffffff, 0x80000000), and I'll bet it works
the way you expect.