for Statement (C)
The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.
The latest version of this topic can be found at 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.
iteration-statement:for ( init-expressionopt ; cond-expressionopt ; loop-expressionopt )statement
Execution of a for statement proceeds as follows:
The
init-expression, if any, is evaluated. This specifies the initialization for the loop. There is no restriction on the type ofinit-expression.The
cond-expression, if any, is evaluated. This expression must have arithmetic or pointer type. It is evaluated before each iteration. Three results are possible:If
cond-expressionis true (nonzero),statementis executed; thenloop-expression, if any, is evaluated. Theloop-expressionis evaluated after each iteration. There is no restriction on its type. Side effects will execute in order. The process then begins again with the evaluation ofcond-expression.If
cond-expressionis omitted,cond-expressionis considered true, and execution proceeds exactly as described in the previous paragraph. Aforstatement without acond-expressionargument terminates only when abreakorreturnstatement within the statement body is executed, or when agoto(to a labeled statement outside theforstatement body) is executed.If
cond-expressionisfalse(0), execution of theforstatement 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 is not 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.
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;
}
Number of spaces: 4 Number of tabs: 2