This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: constant signed/unsigned comparison warning


Matthias Urlichs wrote:

>We were talking about sizeof(). Gcc knows that sizeof 'returns' a smallish
>integer (it's a constant, after all). Smallish integers on one side of a
>comparison can be either signed or unsigned depending on the other side of
>the comparison. You don't see a warning when you compare an integer, be it
>signed or unsigned, with the constant 100...

[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 pretty much the same as

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

which may produce unexpected results.
-- 
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.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]