tags:

views:

1342

answers:

4

In several C++ examples I see a use of the type size_t where I would have used a simple int. What's the difference, and why size_t should be better?

Thank you folks.

+4  A: 

It's because size_t can be anything other than an int (maybe a struct). The idea is that it decouples it's job from the underlying type.

graham.reeds
I think size_t is actually guaranteed to be an aliased for an unsigned integer, so it can't be a structure. I don't have a reference handy to back this up right now, though.
unwind
@unwind: C99:TC3, 7.17 §2
Christoph
+16  A: 

From the friendly Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

Also, check Why size_t matters

João da Silva
+2  A: 

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

Axelle Ziegler
A: 

Another metaphor if you are familiar with Object-oriented programming and Java: It's the difference between

this:

ArrayList var = new ArrayList();

and this:

List var = new ArrayList();

The latter prefers interface over a concrete type for the variable type.

artknish