Re: Comparing singed to unsinged warning
- From: "Alexei A. Frounze" <alexfrunews@xxxxxxxxx>
- Date: Thu, 23 Aug 2007 06:13:27 -0000
On Aug 22, 4:09 pm, Nevil Lesdog <n...@xxxxxxxxx> wrote:
What do you think is the best way to handle a compiler warning about
comparing an unsinged value to a singed 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?
You could compare them using a dedicated function like in this
program:
#include <stdio.h>
#include <limits.h>
int CmpSU (int s, unsigned int u)
// compares signed int s and unsigned int u;
// returns: -1 if s < u
// 0 if s == u
// 1 if s > u
{
if (s >= 0)
{
if ((unsigned int)s < u) return -1;
else if ((unsigned int)s > u) return 1;
return 0;
}
return -1;
}
struct
{
int s;
unsigned u;
} aTestValues[] =
{
{INT_MIN, 0},
{INT_MIN, 1},
{INT_MIN, INT_MAX},
{INT_MIN, UINT_MAX},
{-1, 0},
{-1, 1},
{-1, INT_MAX},
{-1, UINT_MAX},
{0, 0},
{0, 1},
{0, INT_MAX},
{0, UINT_MAX},
{1, 0},
{1, 1},
{1, INT_MAX},
{1, UINT_MAX},
{INT_MAX, 0},
{INT_MAX, 1},
{INT_MAX, INT_MAX},
{INT_MAX, UINT_MAX},
};
int main (void)
{
int i;
for (i = 0;
i < sizeof(aTestValues)/sizeof(aTestValues[0]);
i++)
{
int s = aTestValues[i].s;
unsigned int u = aTestValues[i].u;
printf ("%d %c %u\n",
s,
"<=>"[1+CmpSU(s,u)],
u);
}
return 0;
}
Alex
.
- References:
- Comparing singed to unsinged warning
- From: Nevil Lesdog
- Comparing singed to unsinged warning
- Prev by Date: Re: File included twice
- Next by Date: Re: Two questions about the following lines of code
- Previous by thread: Re: Comparing singed to unsinged warning
- Next by thread: Function prototypes
- Index(es):
Relevant Pages
|
Loading