41 of 208
ZBasic Language Reference 33 ZX Microcontroller Family For <var> = <start-expr> To <end-expr> [ Step <step-expr> ] [<statements>] Next [ <var> ] The <var> element, referred to as the loop index variable, must refer to a previously defined scalar variable (i.e. not an array element) that is either a numeric type or an enumeration type. The <start- expr>, <end-expr> and optional <step-expr> elements must all be the same type as the loop index variable. Example Dim i as Integer For i = 1 To 10 Debug.Print CStr(i) Next i When the For statement begins execution, the <start-expr> is evaluated and the resulting value is assigned to the loop index variable. Then, before executing any statements contained within the body of the For-Next statement, the <end-expr> is evaluated and the value of loop index variable is compared to that value. If the value of the loop index variable is less than or equal to the value of the <end-expr> the statements within the body of the For-Next are executed. This is called the “loop entry test” because it controls whether or not the loop statements are executed. At the bottom of the loop, marked by the Next statement, the loop index variable is modified in preparation for the next iteration of the For-Next loop. If the optional Step <step-expr> is present its value is added to the loop index variable, otherwise the loop index variable is simply augmented by 1. Then control is transferred back to the top of the loop where the loop entry test is performed again. The logic of the For loop in the example above may be exactly duplicated using other statements as illustrated below. You can see that the For loop allows you to express the same logic more concisely. Dim i as Integer i = 1 Do While (i <= 10) Debug.Print CStr(i) i = i + 1 Loop There are several things to note about the For-Next loop. Firstly, it is important to be aware that although the values of the <end-expr> and <step-expr> elements are used multiple times, the expressions are only evaluated once, when the execution of the For-Next begins. This distinction is only important, of course, if these expressions contain references to other variables that might be modified during loop execution or if they involve function calls. Secondly, because the loop entry test checks to see if the loop index variable is less than or equal to the <end-expr> you must choose a data type for the loop index variable that is capable of representing a value that is greater than the value of the <end-expr> . Otherwise, the loop entry test will always be true. Consider this errant example: Dim i as Byte For i = 0 to 255 <statements> Next i This loop will never terminate because the value of i is always less than or equal to 255 since it is a Byte type. Where possible, the compiler will issue a warning if it detects these problematic conditions. Even so, you should develop the habit of considering this potential problem every time you code a For- Next loop.