Re: size_t and int comparison

From: Jerry Coffin (jcoffin_at_taeus.com)
Date: 01/09/05


Date: 9 Jan 2005 13:27:32 -0800


> Two solutions to remove the warning:
>
> 1. Change the type of the variable 'i' to 'size_t'.
> 2. staic_cast i to "unsigned" type.

It's giving you a warning because strlen returns a size_t, which is
some unsigned type. You're comparing it to 'i', which is a (signed)
int, and comparing a signed to an unsigned can cause rather strange
results (since each type can normally represent some values the other
can't).

It won't warn you, but you're re-computing the length of the string
every time through the loop. This makes your loop O(N * N) instead of
O(N) -- ugly unless your string is _really_ short. I'd use something
like:

for (int i=0; pathcmd[i] != '\0'; i++) {

Or, perhaps just switch to using an std::string, and while you're at
it, you might want to quit using an explicit loop and replace it with
an algorithm instead:

std::for_each(pathcmd.begin(), pathcmd.end(), do_whatever);

and possibly use boost::lambda to create do_whatever on the fly as
well...

--
Later,
Jerry.
The universe is a figment of its own imagination.


Relevant Pages

  • Re: GCC 3.3.1, new warnings with <limits>
    ... > on an unsigned type which does a < compareison. ... and thus prints out the warning. ... If I take the following preprocessed source and compile it ...
    (freebsd-current)
  • Use Microsoft CDO Example
    ... MSVC 6 on Windows XP. ... warning C4192: automatically excluding 'ISupportErrorInfo' while importing type library ... unary minus operator applied to unsigned type, ...
    (microsoft.public.win32.programmer.messaging)
  • Re: [PATCH] Remove pointless <0 comparison for unsigned variable in fs/fcntl.c
    ... > would be a lot easier to understand than comparing with 0xffff. ... That was not the point of the example Linus gave. ... pid_t is 16bit or less you won't get a warning when pid_t is greater than ... To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.kernel.org More majordomo info at http://vger.kernel.org/majordomo-info.html Please read the FAQ at http://www.tux.org/lkml/ ...
    (Linux-Kernel)
  • Re: Comparing singed to unsinged warning
    ... comparing an unsinged value to a singed value? ... Look at the code and make darned sure you understand why the warning ... cast, which will at least indicate that you did it on purpose. ... This makes disabling it undesirable. ...
    (comp.lang.c)
  • Re: [PATCH] i386, nmi: signed vs unsigned mixup
    ... signed and unsigned type in conditional expression (2109 instances ... So for the signedness related warnings we have a total of 14491 warnings. ... warning: ...
    (Linux-Kernel)