views:

185

answers:

4

Possible Duplicate:
When to use std::size_t?

I have a lot of constants in my code that are unsigned numbers, e.g. counters, frequency cutoffs, lengths, etc. I started using std::size_t for all of these, instead of int or unsigned int.

Is that the right thing to do? I started it because the STL containers use it for their sizes, it's used for string position, etc.

+1  A: 

See: http://stackoverflow.com/questions/1951519/when-to-use-stdsize-t

Ash Kim
This should have been a comment to the question.
sbi
+6  A: 

std::size_t is the type to use for counting memory locations, like array lengths, the size of objects, etc. STL containers are using container_type::size_type, which will usually map to std::size_t, but isn't guaranteed to do so.

If you need types for holding non-negative integrals which are not used for the above mentioned purposes, what's wrong with unsigned short, unsigned int, and unsigned long?

sbi
+2  A: 

You can use size_t for variables that represent sizes of objects stored in memory. But there's not much reason to use it for anything else. It exists mainly because unsigned int might not be sufficiently wide to represent the size of a memory object. (Consider an architecture with 16-bit ints but a 32-bit address space.)

Willis Blackburn
+3  A: 

size_t is actually a typedef defined in stddef.h and it's platform dependent, so you can't really make any assumptions about it. On gcc 4.4 (i486) it's defined as a long unsigned int, unless the OS already defines it, so for instance on Free BSD 5 on a i386 machine it's gonna be unsigned int whilst on a ia64 machine it's gonna be a unsigned long. So for instance if you try to do something like

size_t i;
...
char buf[4];
sprintf(buf,"%u",i);

Sometimes it's gonna run, but on some platforms/compilers you're gonna get a buffer overflow.

My point is that this can cause some nasty portability issues if you have to make assumptions about the size/type of size_t.

kiwi