Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use size_t in C++?

Tags:

c++

types

I've seen people use size_t whenever they mean an unsigned integer. For example:

class Company {
  size_t num_employees_;
  // ...
};

Is that good practice? One thing is you have to include <cstddef>. Should it be unsigned int instead? Or even just int?

Just using int sounds attractive to me since it avoids stupid bugs like these (because people do often use int):

for(int i = num_employees_ - 1; i >= 0; --i) {
   // do something with employee_[i]
}
like image 479
Frank Avatar asked Jul 11 '09 16:07

Frank


People also ask

Should you use Size_t in C?

Using size_t appropriately can improve the portability, efficiency, or readability of your code. Maybe even all three. Numerous functions in the Standard C library accept arguments or return values that represent object sizes in bytes.

Should I use Size_t instead of int?

When writing C code you should always use size_t whenever dealing with memory ranges. The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic.

What is the point of Size_t?

size_t type is a base unsigned integer type of C/C++ language. It is the type of the result returned by sizeof operator. The type's size is chosen so that it can store the maximum size of a theoretically possible array of any type. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.

Should I use Size_t or std :: Size_t?

So yeah, both are same; the only difference is that C++ defines size_t in std namespace.


1 Answers

size_t may have different size to int.

For things like number of employees, etc., this difference usually is inconsequential; how often does one have more than 2^32 employees? However, if you a field to represent a file size, you will want to use size_t instead of int, if your filesystem supports 64-bit files.

Do realise that object sizes (as obtained by sizeof) are of type size_t, not int or unsigned int; also, correspondingly, there is a ptrdiff_t for the difference between two pointers (e.g., &a[5] - &a[0] == ptrdiff_t(5)).

like image 86
Chris Jester-Young Avatar answered Sep 19 '22 15:09

Chris Jester-Young