uint8_t i=0;//a "global" variable, scoped to be used in the for loop and after it, not just declared in the for loop's opening line
for(i=0; i<value; i++){//assume value is <255
//do something
Serial.print(i);
Serial.print(",");
}
Serial.println("done");
Serial.println(i);
When this runs i counts up from 0 to value-1. Then the loop exits, and after the loop is done, i will now be equal to value.
Can this behaviour be relied on, or might it differ with different compiler versions or, outside of arduino usage where printf might be needed rather than Serial.print, in C vs C++?
Does a for loop acting to iterate up to some value always guarantee another iteration will be done at exit time? Or can some compilers choose not to make this final iteration to i?
This is particularly applicable when using a loop which might have a break because of a mesured condition, or might time out, and telling afterwards whether it timed out:
It feels like asking whether for always acts more like while or do...while?
Does it apply to all major programming languages? C, C++, Python, Java... Or would whether i gets that final iteration added in these sort of circumstances vary by language?
@infraviolet I believe you are confusing cause with effect. When i increments the final time to become equal to value, that is what triggers the loop to exit. The loop exiting does not trigger i to increment one final time to become equal to value.
the i < value condition in all languages means that the condition is no longer true when i >= value and a for/while loop will not continue when the condition is no longer true. if "i" is being incremented, it will have the value of "value" after the loop ends
then the index variable i will be local to the body of the loop, and go out of existence when the loop is exited, so therefore would not be available in the same way.
But in the case you are asking about, absolutely reliably the index variable will be where you see it, and that is often used, for example, in the case of a loop that has a break statement in in we can see if the loop finished naturally or was for whatever reason cut short of execute all iterations.