Sunday, February 6, 2022

Visual Foxpro - For End For Command

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:
  1. 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.
  2. 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.
  3. 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.
  4. 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.
Best Practices
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