I'm aware of the nasty stuff that can happen if you mix unsigned's and signed's, and I tend to only ever use unsigned for integers, usually for something like array indices where the value should never be negative, rather than to squeeze another bit.
However, I can see that if an unsigned value is expected, and the user supplies a negative value, you'll get some gigantic number which is essentially garbage. If you then try to access an array or something similar the result will be the same with some out of bound stuff going on, or some allocation will fail. Thinking about it though, with the signed value it could be easier to check for this, because you'll have a negative rather than a huge spurious number.
An example of the kind of place I used unsigned:
template <typename T>
matrix<T>::matrix(const unsigned int r, const unsigned int c) :
rows(r), columns(c)
{
el = new T *[rows];
for (unsigned int i = 0; i < rows; i++)
el[i] = new T[columns];
}
Stylistically I prefer using unsigned because I'm explicitly declaring: this value must be positive, but I can see how this could also cause problems. If a function has unsigned parameters then you know at a glance the value passed must be positive, but then this is probably apparent from the parameter anyway e.g size, index. I guess the question is, what are others' views on using unsigned integers, what is done in practice?

New Topic/Question
Reply



MultiQuote





|