Go Down

Topic: Does for reset itself? (Read 491 times) previous topic - next topic

Vortexnl

Lets say I make a for command that increments a number untill its 255.
After this is finished, will the for reset? or should you manually reset?

Kitep

#1
Jul 06, 2009, 12:43 am Last Edit: Jul 06, 2009, 12:43 am by Kitep Reason: 1
I don't understand the question.

If you have
Code: [Select]
int i;
for (i=0;i<=255;i++) {
 // do stuff
 }


then i==256 when you exit the loop.

Are you perhaps thinking about bytes, which can only hold 0-255?  If you have
Code: [Select]
byte i;
for (i=0;i<=255;i++) {
 // do stuff
 }

then since i is a byte, it can only go from 0-255.  In this case when i++ tries to increment i to 256, it will reset to 0.  Since that's <=255, this particular loop will never end.

Good luck!



Grumpy_Mike

Quote
will the for reset?


It won't reset but it will finish and the instructions following the 'for' will be executed. When all the instructions in the loop() have been done it will run the loop again.

BRuTuS

If you are talking about the variable used in your FOR loop, no the value will not reset.

if you used 'X' for ex, after the FOR loop is done, 'X' will contain 255.

Vortexnl

#4
Jul 06, 2009, 11:37 am Last Edit: Jul 06, 2009, 11:42 am by vortexnl Reason: 1
So, if i=255, then it would increment one more time. therefor resetting to zero and running the loop again?

EDIT:
But if I use an integer with for, should't I be possible to increment it way more than just 255?

Grumpy_Mike

Quote
But if I use an integer with for, should't I be possible to increment it way more than just 255?


Yes I don't know why a byte variable was ever introduced it is irrelevant in this discussion.


Groove

If you use and "int" (aka "short") or "long" type, then the "for" loop should terminate correctly.
Per Arduino ad Astra

Go Up