On Mon, 2003-10-06 at 20:51, Ross Werner wrote:
On Mon, 6 Oct 2003, Matt W. wrote: "A friend" wants to know why we're so inconsistent with our 0-first/1-first counting methods. For example, if your program counts how many tests have been taken and divides the total score, finding the average, we have to start counting by one. (If we start at zero, we find that dividing by zero is not very pretty.) On the other hand, arrays and memory addressing start at zero. Why can't everything just start with one or the other?!
It's not inconsistent. One is counting, the other is addressing. We'd be wasteful to not use zero as a valid address.
Close, but it's even more clear. One is counting, the other is address *offsetting*. It's not just wasteful, but incorrect, to leave out a zero-byte offset. If I have, in C:
int array[3];
Then array = <some address> and looks like this in memory:
+-----+
array -> | | <- array + 0
+-----+
| | <- array + 1
+-----+
| | <- array + 2
+-----+
|*****| <- array + 3 (does not belond to array!)
+-----+indexing that array is then equal to offsetting it, ie:
array[i] = *(array + i)
If the array has 3 elements, then 0 through 2 are valid offsets. If we forget and attempt to use array[3] for the third element, we're accessing beyond the legal bounds of the array and risk a segfault (and if no segfault, really weird program results). The same principle applies to any addressing scheme, so addresses are *always* 0-based.
But with counting, we're counting. When you receive one of something, you have one. When you receive two of something you have two. In some ways you *can* consider it as zero-based as well, though. Whenever I'm counting something in a program, what do I initialize my counter to?
int counter = 0;
while (some condition) { counter++; }See, there's the zero still! That was I can still have none of something. With averages this is tricky, because you have to explicitly check for a DIV0, but that's correct behaviour, because what's the mean of the empty set?
Jacob Fugal
____________________
BYU Unix Users Group http://uug.byu.edu/ ___________________________________________________________________
List Info: http://uug.byu.edu/cgi-bin/mailman/listinfo/uug-list
