For Next -- strange things happening!

Yes John you are right, this is very yesterday’s problem for me, sorry. So picking up the thread, we can put Alberto’s code contributed above in the loop to remedy Xojo’s uint For...Next

if x = 255 then exit // this way Next will not try to increment X beyond Uint8 limit

Which as far as I know is the only For..Next in the known universe to need such remedy. Kind of defeats the purpose of For..Next doesn’t it?
So use Do...Loop with uints instead I say unless one is testing for a condition anyway.

Are you sure? I tried a small test in C:

#include <stdio.h>
#include <stdint.h>

int main(int argc, char **argv) {
	uint8_t i;
	for (i = 0; i <= 255; i++) {
		printf("%d\
", i);
	}
	printf("Finally %d\
", i);
	return 0;
}

On my Mac (compiler idents as “Apple LLVM version 9.0.0 (clang-900.0.39.2)”), the loop never ends. If coded as for (i=0; i <256; i++) the compiler throws “warning: comparison of constant 256 with expression of type ‘uint8_t’ (aka ‘unsigned char’) is always true.”

Same thing happens in VS C++, and in VS C# too (gets stuck in loop), although VB does raise an exception due to overflow.

I’m not a C guy but aren’t you incrementing before the print statement so that your 0 index has already turned to a 1 in the first loop? In BASIC dialects For 0 starts the first pass of the loop with the index value of 0, For 1 starts the first pass of the loop with the index value of 1. Or am I mistaken about this?

To quote Xojo’s language reference for example :

[quote]
By default the counterValue is changed by 1 at the end of each loop (when the Next statement is reached or a Continue is invoked within the loop.[/quote] [Emphasis added]

for (i = 0; i <=255; i++) { printf("%d\
", i); }
  1. Set i to zero.
  2. Test against less-than-or-equal-to 255. If false, exit the loop.
  3. If true, execute the code block within the {} brackets.
  4. At the end of the code block, increment i.
  5. Go to step 2.

It starts printing at 0, not 1, as i is equal to 0 the first time through.

But the important thing is what happens when i = 255. Note that i is incremented before the test, so it goes from 255 to 0 before the <=255 test is performed.

When reading your code from left to right it looks like i is incremented after the test but I take your word for it.

But if in the case of For..Next (not being C/C++) the increment only happens “when the Next statement is reached” - as Xojo’s Language Reference puts it - then the test in Xojo must occur after the increment to keep the For...Next rules of the language consistent and in tact; and which increment should not occur if the specified valid range is already exhausted!

However, using Do...Loop instead of For...Next makes for more explicit code with better control IMHO. And if I were king of the universe I would abolish For...Next which of course Xojo Inc. can’t.