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.
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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With