Sunday, December 27, 2009

size_t in C/C++

size_t

size_t corresponds to the integral data type returned by the language operator sizeof and is defined in the header file (among others) as an unsigned integral type.

This is an unsigned integer type used to represent the sizes of objects. The result of the sizeof operator is of this type, and functions such as malloc and memcpy accept arguments of this type to specify object sizes.

It is also used as the return type for strcspn, strlen, strspn and strxfrm to return sizes and lengths.

Here is a sample problem, which will help us understand it better:
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++?

Change 'i' to type 'size_t'.

Or better yet, replace your char array 'pathcmd'
with a 'std::string' object, and write:

std::string pathcmd("whatever");
for(std::string::size_type i = 0; i < pathcmd.size(); ++i)
/***end of example*****/


Careful--->
assigning size_t type variable to int works fine.
Only if the value in the size_t variable can be represented by int. Otherwise you've invoked undefined behavior. The only way this assignment could be safe is if size_t is smaller than int, which isn't a common case.


in printf size_t has format specifier as %z ( courtesy Amitesh Singh, thanks :)

2 comments:

  1. size_t is not only unsigned, but is platform-dependent as far as the length of the type is concerned. On 64-bit platforms you will find that size_t is usually 64 bits in length (or 8 bytes, or a double word).

    This matters especially if you intend to do I/O on size_t types.

    I hope this helps!

    ReplyDelete
  2. Yes, definitely helpful information.
    Thanks Micheal.

    ReplyDelete