for
Statement (C)
The for
statement lets you repeat a statement or compound statement a specified number of times. The body of a for
statement is executed zero or more times until an optional condition becomes false. You can use optional expressions within the for
statement to initialize and change values during the for
statement's execution.
Syntax
iteration-statement
:
for
(
init-expression
opt ;
cond-expression
opt ;
loop-expression
opt )
statement
Execution of a for
statement proceeds as follows:
The
init-expression
, if any, is evaluated. It specifies the initialization for the loop. There's no restriction on the type ofinit-expression
.The
cond-expression
, if any, is evaluated. This expression must have arithmetic or pointer type. It's evaluated before each iteration. Three results are possible:If
cond-expression
istrue
(nonzero),statement
is executed; thenloop-expression
, if any, is evaluated. Theloop-expression
is evaluated after each iteration. There's no restriction on its type. Side effects will execute in order. The process then begins again with the evaluation ofcond-expression
.If
cond-expression
is omitted,cond-expression
is considered true, and execution proceeds exactly as described in the previous paragraph. Afor
statement without acond-expression
argument terminates only when abreak
orreturn
statement within the statement body is executed, or when agoto
(to a labeled statement outside thefor
statement body) is executed.If
cond-expression
isfalse
(0), execution of thefor
statement terminates and control passes to the next statement in the program.
A for
statement also terminates when a break
, goto
, or return
statement within the statement body is executed. A continue
statement in a for
loop causes loop-expression
to be evaluated. When a break
statement is executed inside a for
loop, loop-expression
isn't evaluated or executed. This statement
for( ; ; )
is the customary way to produce an infinite loop, which can only be exited with a break
, goto
, or return
statement.
Example
This example illustrates the for
statement:
// c_for.c
int main()
{
char* line = "H e \tl\tlo World\0";
int space = 0;
int tab = 0;
int i;
int max = strlen(line);
for (i = 0; i < max; i++ )
{
if ( line[i] == ' ' )
{
space++;
}
if ( line[i] == '\t' )
{
tab++;
}
}
printf("Number of spaces: %i\n", space);
printf("Number of tabs: %i\n", tab);
return 0;
}
Output
Number of spaces: 4
Number of tabs: 2