size_t corresponds to the integral data type returned by the language operator sizeof and is defined in the
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 :)
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).
ReplyDeleteThis matters especially if you intend to do I/O on size_t types.
I hope this helps!
Yes, definitely helpful information.
ReplyDeleteThanks Micheal.