The size_t Data Type


A new data type that you will encounter in reading the documentation for the C and C++ string functions is size_t. For example, here is the prototype for the strlen() function:

size_t strlen(const char* str);

And here is the prototype for the length() member function of the C++ string class:

size_t length() const noexcept;

The name size_t essentially means "size type", and you will typically see this data type used to specify the size or length of things - like the length of a C string returned by the strlen() function, for example.

This is not one of the "built-in" data types of C/C++. Instead, it was defined in several header files using the typedef command. The exact data type is implementation specific, but is normally some form on unsigned integer type.

An unsigned integer type is an integer that can be 0 or greater than 0 but cannot be negative. If you think about it a bit, it makes sense to use this data type for something like the length of a C string. You can have a C string that is length 0 (nothing but a null character), but how could you possibly have a string with a negative length?

For the most part, you can treat a size_t variable as if it were an integer without any issues. One problem that does come up however is that the C++ compiler will give you a warning if you compare an integer to an unsigned integer type:

string str = "something something something";

for (int i = 0; i < str.length(); i++)
    str[i] = toupper(str[i]);

Here, i is data type int while the return value from the length() member function is data type size_t (an unsigned integer type). The compiler will flag this comparison with a warning.

There are two ways to fix this kind of warning.

  1. We can type cast the return value of the length() member function to an integer.

    string str = "something something something";
        
    for (int i = 0; i < (int) str.length(); i++)
        str[i] = toupper(str[i]);
    
  2. We can declare i as data type size_t instead of data type int.

    string str = "something something something";
        
    for (size_t i = 0; i < str.length(); i++)
        str[i] = toupper(str[i]);