FOR nVar = nInitialValue TO nFinalValue [STEP nIncrement] commands [EXIT] [LOOP] ENDFOR | NEXT }There are a few interesting aspects of this looping construct that newcomers to VFP may not know:
- nVar is a variable just like any other VFP variable. As such, you must declare it properly (usually as LOCAL) to be sure you don't change the value of a same-named variable in a higher routine, etc.
- If you complete the processing without a (premature) EXIT, the value of variable nVar is still accessible, and can be tested to determine that no EXIT occurred. Note: This technique, while allowable, may impede code maintenance and readability. See "Best Practices" below.
- If the value of nStep is the default of 1, the value of nVar will be nFinalValue + 1 if no EXIT occurred. If nStep is some value other than 1, nVar can be determined by:
nInitialValue + nStep + FLOOR( ( nFinalValue - nInitialValue ) / nStep ) * nStep. - If nFinalValue (or nStep) are specified by variables, you cannot affect the number processing loops by changing those values within the loop. This is different from DO WHILE and SCAN WHILE constructions, where expressions are re-evaluated upon each traversal through the loop.
While using the value of the loop counter to indicate how the loop terminated may indeed work, I think the fact that few people know about it would make the use of it for that purpose confusing at the very least, and the programmer should document the behavior for maintenance reasons. My preference would be to define a separate variable such as 'llExit', initialize it to .F. at the top of the loop, and then if the code reaches the EXIT line, set it to .T. before exiting. This would be much clearer for future programmers to follow. -- Ed Leafe
No comments:
Post a Comment