Though it seems you have solved your problem by finding an alternative. For you to know:
size_t is just an unsigned int.
Why should you use it instead of int when referring to sizes or array indices? To avoid having negative sizes or positions and subsequent illegal memory access... By using size_t you don't have to check if the variable is > 0 because it will always be by definition.
But, size_t can be treacherous. If you happen to assign, e.g -2 to a size_t variable, the number will be substracted from the size_t's limit and you'll probably get a big positive number that will also result in illegal memory access...
size_t may also be useful when you need to use integer's memory space at full. You surely know that if in your platform (signed) int is 4-bytes long, you'll be able to use 2-byte long positives and 2-byte long negatives (aprox.). With size_t, unsigned int, you can use 4-byte long positive numbers, specially useful when you certainly know that some variable will never hit a negative value.
EDIT: Oh man... now I realize what was my mistake.. yeah... 31 bits = 2 bytes... great! Sorry.
It's because, to represent negative values, you usually use the Two's complement (see http://en.wikipedia.org/wiki/Two%27s_complement).
What really happens is that, when you have a signed data type, you have to hold the sign somewhere. Conventionally, the first bit is used to represent the sign: 0 is +, 1 is -. So, in a (signed char) value, your number will have to fit in 31-bits, so the real upper limit is reduced to the half... to both sides of zero. In a unsigned value, all 32-bits are used to represent the value.
Last edited by nvteighen; August 23rd, 2008 at 04:48 PM.
Yes, I already knew that.
What puzzles me is "2-byte longs". What do you mean by 2 bytes? 31 bits is not 2 bytes, is almost 4!!
size_t is not required to be unsigned int, but rather an unsigned integer type. Well, that is taking things to the limit: in most cases it is unsigned int.
Sadly enough assignment of a negative integer into an unsigned type does not fire warnings... But nevertheless, you only need to care for numbers greater than some limit, which you have to care about in both cases.
Bookmarks