Re: problem with autowiz.c

From: Warren Robbins (robbinsw@ucs.orst.edu)
Date: 12/30/99


The warning itself is a pretty clear indication of the problem.

See below.

On Thu, 30 Dec 1999, Tdz Computing wrote:

[snip]
> autowiz.c: In function `write_wizlist':
> autowiz.c:175: warning: comparison between signed and unsigned
> autowiz.c:195: warning: comparison between signed and unsigned

[snip]
> 175    for (j = 1; j <= (strlen(curr_level->params->level_name) >>1); j++)
> 195    for (j = 1; j <= (IMM_NSIZE - strlen(curr_name->name)); j++)

The variables being compared on line 175 are `j' and
`strlen(curr_level->params->level_name) >> 1'.  One of these variables is
signed, the other is unsigned.

Without looking in the man pages, I'm going to jump to the conclusion that
strlen() returns an unsigned integer, because there is no string of
negative length[1].  It is apparent that the >> 1 operand is being used
for a division of two, which I've never seen the purpose of[2].

Thus, we can assume that `j' is the signed variable, which, although not
seen here, could be negative.

The problem with such a comparison is that instead of being a numeric
value, the left-most bit of a signed variable declares signed-ness.  Let
us assume your platform has integers of 4 bits (as an example for
readability).

Binary Rep.   Signed Integer Value    Unsigned Integer Value
   0001                 1                        1
   0010                 2                        2
   1010                -2                       10

As you can see, the same binary representation that is compared represents
two very different values.  What you might expect to be the number `8',
when stored in a signed four bit chunk of memory, is actually -0, or just
zero.

Your problem basically comes down to this point, the compiler is _warning_
you that you might make such an invalid comparison.  You can dispel the
warning by either:
(a) typecasting one side of the comparison, such as j <= (signed int) ...;
(b) declaring your `j' variable as `unsigned int j;', thereby making both
sides of the comparison of similar signedness.

However, you may note that it _IS_ a warning, and your file is still
compiled.  It may work correctly, unless you get a string of length beyond
the scope of a signed integer.

I recommend solution b.

-k.

[1] - This may be blatantly false.  I'm just using deductive logic, and
don't have specific references to refer to at the moment.

[2] - It may be fractions of fractions of a second quicker, I suppose, but
it may have made it more difficult for you to debug, so you've lost more
time now than you gained by having a quicker operation.


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     |  http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html  |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST