Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
For loop
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Additional semantics and constructs== ===Use as infinite loops=== {{Further|Infinite loop}} This C-style for-loop is commonly the source of an [[infinite loop]] since the fundamental steps of iteration are completely in the control of the programmer. When infinite loops are intended, this type of for-loop can be used (with empty expressions), such as: <syntaxhighlight lang="c"> for (;;) //loop body </syntaxhighlight> This style is used instead of infinite {{code|while (1)}} loops to avoid a type conversion warning in some C/C++ compilers.<ref>{{cite web |title=Compiler Warning (level 4) C4127 |url=http://msdn.microsoft.com/en-us/library/6t66728h.aspx |publisher=Microsoft |access-date=29 June 2011}}</ref> Some programmers prefer the more succinct {{code|for (;;)}} form over the semantically equivalent but more verbose {{code|while (true)}} form. ===Early exit and continuation=== Some languages may also provide other supporting statements, which when present can alter how the for-loop iteration proceeds. Common among these are the [[Break statement|break]] and [[Control flow#Continuation with next iteration|continue]] statements found in C and its derivatives. The break statement causes the innermost loop to be terminated immediately when executed. The continue statement will move at once to the next iteration without further progress through the loop body for the current iteration. A for statement also terminates when a break, goto, or return statement within the statement body is executed.[Wells] Other languages may have similar statements or otherwise provide means to alter the for-loop progress; for example in Fortran 90: <syntaxhighlight lang="Fortran"> DO I = 1, N statements!Executed for all values of "I", up to a disaster if any. IF (no good) CYCLE! Skip this value of "I", and continue with the next. Statements!Executed only where goodness prevails. IF (disaster) EXIT! Abandon the loop. Statements!While good and, no disaster. END DO! Should align with the "DO". </syntaxhighlight> Some languages offer further facilities such as naming the various loop constructs so that with multiple nested loops there is no doubt as to which loop is involved. Fortran 90, for example: <syntaxhighlight lang="Fortran"> X1:DO I = 1, N statements X2:DO J = 1, M statements IF (trouble) CYCLE X1 statements END DO X2 statements END DO X1 </syntaxhighlight> Thus, when "trouble" is detected in the inner loop, the CYCLE X1 (not X2) means that the skip will be to the next iteration for I, ''not'' J. The compiler will also be checking that each END DO has the appropriate label for its position: this is not just a documentation aid. The programmer must still code the problem correctly, but some possible blunders will be blocked. ===Loop variable scope and semantics=== Different languages specify different rules for what value the loop variable will hold on termination of its loop, and indeed some hold that it "becomes undefined". This permits a [[compiler]] to generate code that leaves any value in the loop variable, or perhaps even leaves it unchanged because the loop value was held in a register and never stored in memory. Actual behavior may even vary according to the compiler's optimization settings, as with the Honeywell Fortran66 compiler. In some languages (not [[C (programming language)|C]] or [[C++]]) the loop variable is [[Immutable object|immutable]] within the scope of the loop body, with any attempt to modify its value being regarded as a semantic error. Such modifications are sometimes a consequence of a programmer error, which can be very difficult to identify once made. However, only overt changes are likely to be detected by the compiler. Situations, where the address of the loop variable is passed as an argument to a [[subroutine]], make it very difficult to check because the routine's behavior is in general unknowable to the compiler unless the language supports procedure signatures and argument intents. Some examples in the style of pre-Fortran-90: <syntaxhighlight lang="Fortran"> DO I = 1, N I = 7 !Overt adjustment of the loop variable. Compiler should complain Z = ADJUST(I) !Function "ADJUST" might alter "I", to uncertain effect. PRINT *, (A(I), B(I), I = 1, N, 2) !Implicit for-loop to print odd elements of arrays A and B, reusing "I"... Compiler should complain. PRINT *, I ! What value will be presented? END DO! How many times will the loop be executed? </syntaxhighlight> A common approach is to calculate the iteration count at the start of a loop (with careful attention to overflow as in {{code|1=for i:= 0: 65535 do ... ;}} in sixteen-bit integer arithmetic) and with each iteration decrement this count while also adjusting the value of {{mono|I}}: double counting results. However, adjustments to the value of {{mono|I}} within the loop will not change the number of iterations executed. Still, another possibility is that the code generated may employ an auxiliary variable as the loop variable, possibly held in a machine register, whose value may or may not be copied to {{mono|I}} on each iteration. Again, modifications of {{mono|I}} would not affect the control of the loop, but now a disjunction is possible: within the loop, references to the value of {{mono|I}} might be to the (possibly altered) current value of {{mono|I}} or to the auxiliary variable (held safe from improper modification) and confusing results are guaranteed. For instance, within the loop a reference to element {{mono|I}} of an array would likely employ the auxiliary variable (especially if it were held in a machine register), but if {{mono|I}} is a parameter to some routine (for instance, a ''print''-statement to reveal its value), it would likely be a reference to the proper variable {{mono|I}} instead. It is best to avoid such possibilities. ====Adjustment of bounds==== Just as the index variable might be modified within a for-loop, so also may its bounds and direction. But to uncertain effect. A compiler may prevent such attempts, they may have no effect, or they might even work properly - though many would declare that to do so would be wrong. Consider a statement such as '''for''' i := first : last : step '''do''' A(i) := A(i) / A(last); If the approach to compiling such a loop was to be the evaluation of {{mono|first}}, {{mono|last}} and {{mono|step}} and the calculation of an iteration count via something like {{code|(last - first)/step}} once only at the start, then if those items were simple variables and their values were somehow adjusted during the iterations, this would have no effect on the iteration count even if the element selected for division by {{code|A(last)}} changed. ===List of value ranges=== ALGOL 60, PL/I, and ALGOL 68, allow loops in which the loop variable is iterated over a list of ranges of values instead of a single range. The following PL/I example will execute the loop with six values of i: 1, 7, 12, 13, 14, 15: <syntaxhighlight lang="rexx"> do i = 1, 7, 12 to 15; /*statements*/ end; </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)