Friday, September 26, 2008

size_t

What a pain in the ass.. size_t is the format one should use in for-loops in C/C++.
I've been doing it. I get it, it's sort of like unsigned int, but tailored for addressing memory, so it's going to be scalable on 64 bit (addressing) architectures and also helps using the full 32 bit because of it's unsigned nature (no more oversights where one is limited to access 2GB of memory instead of 4).

Still it's a pain in the ass !
For example size_t becomes ugly with backward for-loops that use the iterator to index a 0-based array, (unsafe):

for (size_t i=vec.size()-1; i >=0; --i)
{
    // ...
}
..if vec.size() is 0, it will underflow (meaning negative overflow actually) and the loop will iterate 4 billion of times instead of 0 times 8)

So, one has to typecast like such, (safe, up to size_t-1's bits):

for (int i=(int)vec.size()-1; i >=0; --i)
{
    // ...
}

..but in most loops one doesn't really have to address 4 billion things, or 2 billions. So, what a pain in the ass to have to worry about underflow !!

bha