Re: Style question: comparison between signed and unsigned?

ig25@rz.uni-karlsruhe.de
Wed, 24 Sep 1997 15:32:10 +0200


In ka.lists.linux.kernel, Matthias Urlichs wrote:

>And because GCC knows how to figure out the size of the struct, but then
>forgets to check if the high bit of that size is set (otherwise you cannot
>run into a problem in the first place).

This is not a bug.

[Sorry to get into C legalese...]

ISO-standard, 6.2.1.2,

[...]

When a signed integer is converted to an unsigned integer with equal
or greater size, [... same size, negative ...]
the value is converted to unsigned by adding to it one greater than
the largest number that can be represented in the unsigned integer
type.

und 6.2.1.5, Usual arithmetic conversions:

...

Otherwise, if either operand has the type unsigned int, the other operand
is converted to unsigned int.

und 6.3.8, Relational Operators

...

If both of the operands have arithmetic types, the usual arithmetic
conversions are performed.

and 6.3.3.4 specifies that sizeof() returns an unsigned integral type,
i.e. size_t.

In other words,

int i = ...;
if (i < sizeof(foo))

is equivalent to

int i = ...;
if (i < 100u)

which may produce fairly unexpected, but mandated results if i < 0.

-- 
Thomas Koenig, Thomas.Koenig@ciw.uni-karlsruhe.de, ig25@dkauni2.bitnet.
The joy of engineering is to find a straight line on a double
logarithmic diagram.

-- 
Thomas Koenig, Thomas.Koenig@ciw.uni-karlsruhe.de, ig25@dkauni2.bitnet.
The joy of engineering is to find a straight line on a double
logarithmic diagram.