Re: size_t and int comparison

From: David Crocker (dcrocker_at_eschertech.ccoomm)
Date: 01/09/05


Date: Sun, 9 Jan 2005 22:03:39 -0000


"tings" <tings668@hotmail.com> wrote in message
news:%RgEd.10483$c13.154@bgtnsc04-news.ops.worldnet.att.net...
> for (int i=0;i < strlen(pathcmd);i++){//this line cause a warning
>
> warning C4018: '<' : signed/unsigned mismatch
>
> strlen returns a number of type 'size_t'. size_t is an unsigned type and
> you are comparing it to an int, a signed type.
>
> Two solutions to remove the warning:
>
> 1. Change the type of the variable 'i' to 'size_t'.
> 2. staic_cast i to "unsigned" type.
>
> Which way is better in C++?
>
(2) is much better. Mixing up 'int' and 'size_t' is a sure way to write
non-portable code. For example, for most 64-bit C++ compilers, size_t is 64
bits whereas int is 32 bits. It's unlikely you would have a string longer
than 4Gb characters even on a 64-bit machine; but if you did, the code would
break.

David Crocker



Relevant Pages

  • Re: size_t and int comparison
    ... > you are comparing it to an int, a signed type. ... > Two solutions to remove the warning: ...
    (comp.lang.cpp)
  • Re: why I cannot stop this loop at 50 points? (code)
    ... int main ... Non-portable code is off-topic here, so if you post to the ... They can invoke undefined behavior only if time_t is a floating-point ... In practice, I've never seen a system where it is. ...
    (comp.lang.c)
  • Re: size_t and int comparison
    ... > you are comparing it to an int, a signed type. ... > Two solutions to remove the warning: ... (if the code in your loop does not modify the string, ...
    (comp.lang.cpp)
  • Re: Intel Atom vs ARM
    ... so using 'int' without care often results in non-portable code. ... years ago) had a default integer type that was 16-bits, for compatibilty. ...
    (comp.arch)
  • Re: K&R 2 exercise 2-3
    ... > int lower ... Already non-portable code, with foul formatting. ... four blanks you could have saved. ...
    (comp.lang.c)