for..next and do...loop confusion

SilentScreamer

Senior Member
I have posted two bits of code below, they both pause for 10,000ms but the do...loop option is 1 byte smaller. Is there any advantage to using for..next over do...loop other than it is a little less to type?

Code:
for b0 = 0 to 100
	pause 10
	next
Code:
do
	inc b0
	pause 10
	loop until b0 = 100

EDIT: Before anyone says anything I know pause 10000 works, I did this as a test to see if for...next used less space.
 

Dippy

Moderator
Dunno.

You've got a nice choice which to use.

There are many advantages of the Do/Loop structure over For/Next.
1. You have more control over conditionals.
2. Generally safer (in many laguages, not sure about PICAXE) for a premature loop exit.
3. Test the conditional before the loop or after.
4. The conditional needn't be the loop variable.
5. Variable increments for loop variable.

There maybe more , but my kettle is boiling.
 

Texy

Senior Member
You say its '1 byte smaller', but you haven't initialised b0 at the beginning,
or did you take that into account?

Texy
 

SilentScreamer

Senior Member
Thanks for the post Dippy, I hadn't thought about those advantages.

Also a very good point Texy, I didn't need to with it being at the top of a program. Adding "b0 = 0" adds a further 3 bytes removing the entire point. I think that solves it. :eek:
 

hippy

Ex-Staff (retired)
The general case equivalence of -

For var = first To last Step +/- step
Next

is

var = first
Do
var = var +/- step
Loop Until var < first Or var > last

And the FOR-NEXT will be shorter than DO-LOOP. However, where you can drop parts of that out, you can use DO-LOOP to achieve shorter code. The FOR-NEXT is (AFAIR) slightly faster to execute.
 
Top