tags:

views:

277

answers:

4

This is probably a C++ 101 question: I'm curious what the guidelines are for using size_t and offset_t, e.g. what situations they are intended for, what situations they are not intended for, etc. I haven't done a lot of portable programming, so I have typically just used something like int or unsigned int for array sizes, indexes, and the like. However, I gather it's preferable to use some of these more standard typedefs when possible, so I'd like to know how to do that properly.

As a follow-up question, for development on Windows using Visual Studio 2008, where should I look to find the actual typedefs? I've found size_t defined in a number of headers within the VS installation directory, so I'm not sure which of those I should use, and I can't find offset_t anywhere.

+1  A: 

offset_t isn't mentioned at all in my copy of the C++ standard.

size_t on the other hand, is meant simply to denote object or array sizes. A size_t is guaranteed to be big enough to store the size of any in-memory object, so it should be used for that.

jalf
A: 

You use size_t whenever the C++ language specification indicates that it is used in a particular expression. For example, you'd use size_t to store the return value of sizeof, or to represent the number of elements in an array (new[] takes size_t).

I've no idea what offset_t is - it's not mentioned once in ISO C++ spec.

Pavel Minaev
+5  A: 

You are probably referring to off_t, not offset_t. off_t is a POSIX type, not a C type, and it is used to denote file offsets (allowing 64-bit file offsets even on 32-bit systems). C99 has superceded that with fpos_t.

size_t is meant to count bytes or array elements. It matches the address space.

Martin v. Löwis
size_t has the size needed to contains the size of the largest object, not necessarily the whole address space (think about 16 bit segmented architectures).
AProgrammer
@AProgrammer: I deliberately used the vague "matches" to describe how size_t is related to the address space. You are right: size_t is defined to be the result type of the sizeof operator.
Martin v. Löwis
Sounds like I should be using size_t for the purposes you describe, and not messing with offset_t. Thanks for the info.
Charlie
+2  A: 

Instead of offset_t do you mean ptrdiff_t? This is the type returned by such routines as std::distance. My understanding is that size_t is unsigned (to match the address space as previously mentioned) whereas ptrdiff_t is signed (to theoretically denote "backwards" distances between pointers, though this is very rarely used).

fbrereto
Interesting addition to the discussion - I wasn't aware of ptrdiff_t, but it sounds useful.
Charlie