Artifact a42a3b884b114f64eefb04450909aa78ffea19ae6428170e2805d2bc82aa247e:
- File doc/markdown/for.md — part of check-in [bb08aafe0a] at 2025-07-15 19:41:45 on branch tip-700 — some non-change cosmetics to make the ctags implementation in Geany 2.1 partly happy again (user: Torsten, size: 2776) [annotate] [blame] [check-ins using]
CommandName: for ManualSection: n Version: unknown TclPart: Tcl TclDescription: Tcl Built-In Commands Links:
- break(n)
- continue(n)
- foreach(n)
- while(n) Keywords:
- boolean
- for
- iteration
- loop Copyright:
- Copyright (c) 1993 The Regents of the University of California.
- Copyright (c) 1994-1997 Sun Microsystems, Inc. ---
Name
for - 'For' loop
Synopsis
::: {.synopsis} ::: [for]{.cmd} [start]{.arg} [test]{.arg} [next]{.arg} [body]{.arg} :::
Description
For is a looping command, similar in structure to the C fBforfR statement. The fIstartfR, fInextfR, and fIbodyfR arguments must be Tcl command strings, and fItestfR is an expression string. The fBforfR command first invokes the Tcl interpreter to execute fIstartfR. Then it repeatedly evaluates fItestfR as an expression; if the result is non-zero it invokes the Tcl interpreter on fIbodyfR, then invokes the Tcl interpreter on fInextfR, then repeats the loop. The command terminates when fItestfR evaluates to 0. If a fBcontinuefR command is invoked within fIbodyfR then any remaining commands in the current execution of fIbodyfR are skipped; processing continues by invoking the Tcl interpreter on fInextfR, then evaluating fItestfR, and so on. If a fBbreakfR command is invoked within fIbodyfR or fInextfR, then the fBforfR command will return immediately. The operation of fBbreakfR and fBcontinuefR are similar to the corresponding statements in C. fBForfR returns an empty string.
Note that fItestfR should almost always be enclosed in braces. If not, variable substitutions will be made before the fBforfR command starts executing, which means that variable changes made by the loop body will not be considered in the expression. This is likely to result in an infinite loop. If fItestfR is enclosed in braces, variable substitutions are delayed until the expression is evaluated (before each loop iteration), so changes in the variables will be visible. See below for an example:
Examples
Print a line for each of the integers from 0 to 9:
for {set x 0} {$x<10} {incr x} {
puts "x is $x"
}
Either loop infinitely or not at all because the expression being evaluated is actually the constant, or even generate an error! The actual behaviour will depend on whether the variable fIxfR exists before the fBforfR command is run and whether its value is a value that is less than or greater than/equal to ten, and this is because the expression will be substituted before the fBforfR command is executed.
for {set x 0} $x<10 {incr x} {
puts "x is $x"
}
Print out the powers of two from 1 to 1024:
for {set x 1} {$x<=1024} {set x [expr {$x * 2}]} {
puts "x is $x"
}