Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size_t vs int in C++ and/or C

Tags:

c++

c

size-type

Why is it that in C++ containers, it returns a size_type rather than an int? If we're creating our own structures, should we also be encouraged to use size_type?

like image 717
John Jiang Avatar asked Jun 15 '09 02:06

John Jiang


People also ask

Should you use int or Size_t?

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.

Can you compare Size_t and int in C?

It is okay to compare a size_t value with an int value, the int value will be implicitly converted to unsigned type. Some compilers will issue a warning when you mix signed and unsigned types in comparisons.

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.


1 Answers

In general, size_t should be used whenever you are measuring the size of something. It is really strange that size_t is only required to represent between 0 and SIZE_MAX bytes and SIZE_MAX is only required to be 65,535...

The other interesting constraints from the C++ and C Standards are:

  • the return type of sizeof() is size_t and it is an unsigned integer
  • operator new() takes the number of bytes to allocate as a size_t parameter
  • size_t is defined in <cstddef>
  • SIZE_MAX is defined in <limits.h> in C99 but not mentioned in C++98?!
  • size_t is not included in the list of fundamental integer types so I have always assumed that size_t is a type alias for one of the fundamental types: char, short int, int, and long int.

If you are counting bytes, then you should definitely be using size_t. If you are counting the number of elements, then you should probably use size_t since this seems to be what C++ has been using. In any case, you don't want to use int - at the very least use unsigned long or unsigned long long if you are using TR1. Or... even better... typedef whatever you end up using to size_type or just include <cstddef> and use std::size_t.

like image 99
D.Shawley Avatar answered Sep 19 '22 00:09

D.Shawley