Strange multiplication ?

Karl Heuer karl at haddock.ima.isc.com
Sun Jun 17 11:00:09 AEST 1990


In article <1790 at krafla.rhi.hi.is> frisk at rhi.hi.is (Fridrik Skulason) writes:
>[On a machine with 8-bit char, 16-bit int, and 32-bit long,
>	unsigned char a = 255;
>	unsigned long i = 256 * a;
>produces 65280 on some compilers, -256 on others.]  I had thought that when
>one operand ("a" in this case) was unsigned, ...

It's an unsigned char.  Since C has no char-typed rvalues, it promotes to
unsigned int (in the unsigned-preserving model) or signed int (in the
value-preserving model).  An ANSI compiler must use the value-preserving
model, in which the computation overflows but probably generates the value
-256.  If the compiler is high-quality, it will also warn about your using a
questionably-signed expression in a signedness-sensitive context.

See also <16836 at haddock.ima.isc.com>, where we just finished discussing a
similar problem.

Karl W. Z. Heuer (karl at kelp.ima.isc.com or harvard!ima!karl), The Walking Lint



More information about the Comp.lang.c mailing list