Francois Grieu <fg****@francenet.fr> writes:
A true story: one C compiler for an embedded processor that
I use claims " ANSI '89 compatibility ". But when I upgraded
from version 2.30 to 2.30.01, some previously working code
misbehaved. After reduction, it turns out that for
unsigned char foo = 0x400000*3/0x40000;
the former compiler set foo to 0x30, and the later 0xF0.
All versions of the compiler agree on
foo = 0x400000*3L/0x40000; /* 0x30 */
foo = 0xC00000/0x40000; /* 0x30 */
foo = 0x400000*3>>18; /* 0x30 */
foo = 0x40000*3/0x4000; /* 0x30 */
The outcome of <limits.h> is that
INT_MAX is 32767
LONG_MAX is 0x7fffffff
but it turns out the compiler has a an extra non-standard
"short long" integer type, and
SLONG_MAX is 0x7fffff
Is the newer compiler wrong ?
Yes, I believe it is.
Adding a "short long" type should be ok, since it can only be used by
a program that would be illegal in strict ANSI mode.
Adding SLONG_MAX to <limits.h> is non-conforming, but it's not going
to be a problem unless the user program tries to define that
identifier for itself.
But I think the real problem is that it treats the hex constants as
being of type "short long".
The type of a hex constant is the first of
int
unsigned int
long
unsigned long
in which its value will fit (C99 adds long long and unsigned long
long). In this case, both 0x400000 and 0x40000 should be of type
long. Apparently the compiler chooses to treat them as constants of
type "short long", which would make perfect sense if "short long" were
part of the language.
On the other hand, the declaration
unsigned char foo = 0x400000*3/0x40000;
is non-portable, and would legitimately yield the same result if
INT_MAX were 0x7fffff. It might be better to specify the types
explicitly:
unsigned char foo = 0x400000UL*3/0x40000UL;
or simply:
unsigned char foo = 0x30;
if that's what you want. (The latter probably doesn't apply, since
you said it was the result of reducing the actual code.)
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.