Digest #54 2019-05-22
What is supposed to happen if the index overflows the upper value of an int -- or the lower bound of negative int? I.E. for a 16-bit system, when the index + increment goes over 32767 but never equals 32767, like counting 10 +LOOP and the index is 32765? There are obviously ways to test for this, but is that expected, or is this one of those "don't do that" situations? Strictly speaking, the standard does say the loop terminates when the index crosses the boundary between limit and limit-1, which is pretty easy to define for all positive limits, but not so for a negative limit of -32768. I'm inclined to go for the "don't do that" option, but maybe that's just laziness. Testing for this involves either extension to double-width values within the runtime code for +LOOP, or some minor headache code to avoid the over/underflow by testing if the difference between index and the MAX/MIN int is less than the increment. I guess it could be specified as implementation-dependent. But it seems the behavior in this condition should at least be mentioned.
After realizing that +LOOP can overflow or underflow, it occurred to me...is that state something that ALL the arithmetic operators should detect? Should it be 1) ignored, 2) a flag that a program can test, 3) an error/exception?? Maybe this issue is addressed somewhere in sections 1-4 of the Standard?
Yes, seems like an error to me, too. Thanks.
+n2 means that n2 is non-negative. It may be zero. (+n1, too, but for n1 non-zero-ness is specified in the prose).
I'll assume that you use 2s-complement representation for negative numbers here (which will be required in the next standard after Forth-2012); the answer is more complex for other integer representations.
Note that the loop control parameters can be either signed or unsigned, and +LOOP has to work for both. For systems with 2s-complement representation for signed numbers, the way to go is to use circular arithmetic: compute x=(index-limit)+minint, and observe if the addition x+n crosses the boundary between minint and maxint. Many architectures report this through the overflow flag. If you don't have or cannot use the overflow flag, look at the source code of (+LOOP) in Gforth for another way to implement +LOOP with circular arithmetic.
Oh, thank. Forget that
+n does not mean positive, but non-negative.
OK...this is just two's-complement overflow, it seems. That's pretty straightforward. I am using 2C arithmetic, but my CPU doesn't have an overflow flag (I'm working with a homebrew 8085 system). It's pretty easy to detect this just by looking at the signs of the index and increment and the sign of the sum. Thanks! It does seem like the overflow condition should be explicitly mentioned in the description of this word, even though it is implied by the wording. Better to bring this issue up right where everyone can see it clearly.