Re: warning - comparing a signed value to an unsinged value

From: CBFalconer (cbfalconer_at_yahoo.com)
Date: 10/20/03


Date: Mon, 20 Oct 2003 21:22:46 GMT

Kevin Goodsell wrote:
>
> What do you think is the best way to handle a compiler warning
> about comparing an unsigned value to a signed value? Cast to
> silence it? Disable that warning altogether? Or just live with it?
>
> On one hand, the warning *could* be useful. Most of the time I get
> it in cases where I know the comparison is safe, but it's not hard
> to imagine that this won't always be the case. This makes
> disabling it undesirable. Casting is a workable solution, but I
> worry that changes in the code later could introduce errors that
> go undetected due to the cast. And I think we all hate not having
> a "clean" compile (if only because having a bunch of warnings that
> you expected makes it more difficult to spot the ones you didn't
> expect).
>
> What is your opinion?

Spend a little time thinking. Assume we are talking about signed
and unsigned ints. Now, if the unsigned is larger than INT_MAX,
it is obviously larger than the int. If the int is negative, it
is obviously smaller than the unsigned. Having eliminated these
cases you can safely cast the int into unsigned, and then
compare. In fact, all you need to eliminate is the negative case.

-- 
Chuck F (cbfalconer@yahoo.com) (cbfalconer@worldnet.att.net)
   Available for consulting/temporary embedded and systems.
   <http://cbfalconer.home.att.net>  USE worldnet address!


Relevant Pages

  • Re: Comparing singed to unsinged warning
    ... Nevil Lesdog wrote: ... What do you think is the best way to handle a compiler warning about ... comparing an unsinged value to a singed value? ... later could introduce errors that go undetected due to the cast. ...
    (comp.lang.c)
  • Re: Comparing pointers
    ... Typecast the pointers to 'unsigned int' before comparing them. ... Presuming you mean "cast", how would that help to establish whether they ...
    (comp.lang.c)
  • Re: warning - comparing a signed value to an unsinged value
    ... you are comparing the value in 'i' with a size_t. ... As I told pete, 'SomeFunc' is ... but the interface requires an int. ... So in short, your answer is "In my opinion, use a cast". ...
    (comp.lang.c)
  • Re: warning - comparing a signed value to an unsinged value
    ... >> What do you think is the best way to handle a compiler warning ... > it is obviously larger than the int. ... > cases you can safely cast the int into unsigned, ... Say one wants to compare a return value from a function to sizeof(some ...
    (comp.lang.c)
  • Re: Comparing singed to unsinged warning
    ... comparing an unsinged value to a singed value? ... Rewrite the code so that there is no singed/unsinged mismatch, ... later could introduce errors that go undetected due to the cast. ... a leap from one signedness to the other is necessary. ...
    (comp.lang.c)