OK so this is the action of the usual FOR NEXT loop
notice that things go wrong when B is a _UNSIGNED _BYTE
B has a value of 255 and then is incremented and so now equals zero. The FOR NEXT goes into an endless loop but as we know that does not happen - confused?
Hit ESCAPE key if you run the code
I suppose whoever coded the original FOR NEXT loop noticed that wrap around, so had to add extra code to prevent the endless loop.
However, the following code has only one IF condition and after exit the B counter has a value that matches A
Nothing is going wrong, except the programmer’s basic knowledge is flawed and they need to go back to school.
DIM b AS _UNSIGNED _BYTE
IF b > 255 THEN …..
Now tell me, what value you can assign to b to EVER make that IF statement a true condition so that it triggers??
b is an unsigned byte, as defined. It’s value can ONLY be 0 to 255, and defined by the programmer. Ergo, it’ll NEVER be greater than 255 and trigger that IF condition which exits the DO… LOOP…
So, with that part of the issue settled, let’s talk about limits of variables.
DIM b AS _UNSIGNED _BYTE
b = 255 + 1
Now, with the above, our variable b is defined as an unsigned byte and has to be in a range from 0 to 255…. Yet, we’re forcibly trying to make it hold a 2-byte value inside a 1-byte block of memory…
How does the language handle that???
You can shove a fully grown man into a child’s pair of pants, and you can’t shove a value of 256 into a single byte. It’s just not possible.
So either you:
1) Cuss loudly, toss the pants on the floor in frustration and stop trying completely — the programming equivalent of tossing a terminating error saying “Variable Out of Bounds”, or some such, which completely halts execution…
OR:
2) You pull the pants up over as much of the ankles and toes as they can fit, and then say, “I did it! Here’s the solution! They fit (this much)…”
In programming, this is a simple case of OVERFLOW math. Your return variable is 1-byte in size, so you return 1 byte. The value 256 is stored in memory as 2 bytes (1 byte representing 1 * 256, and 1 byte representing 0). The return value is the single byte that fits the size of your return variable type — in this case, that’s the byte representing zero, which gives a result of:
b = 255 + 1
PRINT b
b prints out “0”.
You overflowed the maximum value b could hold, so it took the bytes you designated for it and tossed out the rest.
For our pants analogy, we shaved someone’s feet and ankles into the child’s pants, and then cut the leg off above it and said, “See, it works!”
It’s not an error — it’s how the language is designed. If you need b to become a value greater than 255, define it as an INTEGER and not an _UNSIGNED _BYTE.
Or else learn to do this:
b = 0
DO
….stuff
IF b = 255 THEN
EXIT DO
ELSE
b = b + 1
END IF
LOOP
Now you exit before you overflow, and there’s no problem.