comparison between signed int and unsigned int

A

Alex

I have a problem about the comparison between signed and unsigned
integer.
See the following code:

int foo()
{
int i;
unsigned int j;
if (i < j)
{
...
}
return 0;
}

When I compile it with ccarm(a gcc version released by Wind River
designate for arm), no warning. But when I comile it with ccppc(a gcc
version released by Wind River for PowerPC), there is a warning
"warning: comparison between signed and unsigned".

Who can tell me the reason. Thank.

I also use gcc(x86, pc) test it, no warning.
 
O

Old Wolf

Alex said:
I have a problem about the comparison between signed and unsigned
integer.
See the following code:

int foo()
{
int i;
unsigned int j;
if (i < j)
{
...
}
return 0;
}

When I compile it with ccarm(a gcc version released by Wind River
designate for arm), no warning. But when I comile it with ccppc(a gcc
version released by Wind River for PowerPC), there is a warning
"warning: comparison between signed and unsigned".

Who can tell me the reason. Thank.

This is not a required diagnostic, so it is just up to the compiler
developer whether to give a warning or not. You might find that
some of the other compilers have a switch to enable or disable
this warning (gcc does).

The reason that some compilers would warn, is that signed-
unsigned comparison is a frequent source of bugs, eg.

int i = -1;
unsigned int j = 2;

if ( i > j )
puts("wasn't expecting that");
 
A

Alex

Oh, got it. thank Old Wolf.

And I have another question want to ask you:
int i;
unsigned short j;

if (i < j)
{
...
}

If j was promoted as a signed integer in the comparison? Neither ccppc
nor ccarm gave a warning.
 
M

Michael Mair

Alex said:
Oh, got it. thank Old Wolf.

And I have another question want to ask you:
int i;
unsigned short j;

if (i < j)
{
...
}

If j was promoted as a signed integer in the comparison? Neither ccppc
nor ccarm gave a warning.

If the value range of unsigned short fits completely into the
value range of int (which depends on your implementation),
the value of j indeed is subject to promotion to int.
If, for example, unsigned short has the same width and value
range as unsigned int, you are back in the original situation.
If you want to be portably on the safe side, you can change
the above to
if (i < 0 || i < j)
or even convert one or both of the operands of the second
comparison to an unsigned integer type large enough for both
values (negative values are excluded by the first test).


Cheers
Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top