Re: Unsignedness of std::size_t
Alex Shulgin <alex.shulgin@gmail.com> wrote in
news:1176878747.235284.46220@n76g2000hsh.googlegroups.com:
On Apr 17, 6:53 pm, Kaba <REkalleMOunderscoreVErutane...@hotmail.com>
wrote:
To give you an example of why unsigned integers should not represent
normal integers:
Let us have:
std::vector<int> a(5);
std::vector<int> b(8);
std::vector<int>::size() returns a std::size_t.
Now conceptually test if an unsigned integer, or a modular integer, is
really a good choice for representing the 'size', by asking the
following questions:
- How much bigger is 'b' than 'a'?
That's easy, it is 'b.size() - a.size()'.
If you know beforehand that b.size() >= a.size(). In this case, yes.
- How much bigger is 'a' than 'b'?
'a.size() - b.size()' ? 2^n - 8?
Well, but this makes no sense. What excuses you from testing a.size()
= b.size() in the first place before performing the subtraction?
The modular integer is a wrong model for the 'size', yet it is
implicated by the 'unsigned'.
No. What is wrong is that the second question makes no sense still
you are trying to find out an answer for it :-)
Probably, you can get away with such a simple function to calculate
distance between two size_t values:
size_t dist(size_t a, size_t b)
{
return a >= b ? a - b : b - a;
}
Here, both dist(a.size(), b.size()) and dist(b.size(), a.size()) are
perfectly valid and meaningful.
I would not say it makes no sense. Replace "how much bigger is" with
"what's the difference between". You are right that your diff does answer
that. It just loses information on the direction of the difference.
But this does highlight the fact that unsigned may not be the right type
for describing the difference between size_t objects if you want it to
provide direction information.
Much as int is the wrong type to describe differences in ints.
a=2,000,000,000 and b=-1,000,000,000. How much bigger is a than b? Oops.
If you don't want to pay attention to the range limits of types, you will
need to use types that deal with them for you. C integer types do not do
that for you. Compilers will often warn you but you can always choose to
use your own types that are smarter and probably slower if the error
checking is worth it to you.
Otis Bricker
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]