ARM Technical Support Knowledge Articles

FOR STATEMENT

Applies to: C Programming Language

Answer


Information in this article applies to:


QUESTION

How does the for C statement work?

ANSWER

The C for statement lets you specify the initialization, test, and update operations of a structured loop in a single statement. The for statement is created as follows:

for (init_exp; cond_exp; update_exp) loop_body_statement

where:

init_exp is an expression that is evaluated before the loop is entered. The value of the expression isn't used for anything; it's the expression's side effects that make init_exp useful. Typically, init_exp initializes a variable that is also used in the other expressions in the for statement. (Such a variable is often called a "loop control variable".)

cond_exp is an expression that is evaluated before each pass through the loop. If the value of the expression is "false" (i.e., compares equal to zero) the loop is exited.

update_exp is an expression that is evaluated at the end of each pass through the loop, after the loop body has been executed, and just before looping back to evaluate cond_exp again. As with init_exp, this expression is only useful for its side effects; the value produced is thrown away. Typically, update_exp changes the value of a loop control variable.

loop_body_statement is any valid C statement or block.

All three of the expressions in a for statement are optional.

If cond_exp is omitted, the compiler treats it as always "true" (i.e., a constant non-zero value).

If both init_exp and update_exp are omitted, the for statement is equivalent to a while statement. (And it should probably be changed to a while statement for the sake of clarity.)

Since cond_expr is checked before every pass through the loop, including the initial pass, it is possible to exit the loop without ever executing loop_body_statement or update_exp.

The following C statements can alter the flow of control in a for statement:

Examples

#include <stdio.h>

void func (void)
{
unsigned int i;

for (i = 0; i < 100; i++)
  printf ("%u
", i);
}

This function outputs the numbers 0 through 99 on separate lines. You can think of this for loop as: "i equals zero; while i is less than 100; execute the contents of the loop; and post-increment i at the end of the loop".

#include <stdio.h>

void func (void)
{
for (;;)
  printf("Hello world
");
}

This function prints "Hello world" forever (or at least until execution of the program is somehow stopped). This is a common way of writing infinite loops, but we feel that the other common way, using while, is clearer:

while (1)
  printf("Hello world
");

Article last edited on: 2004-06-25 11:42:56

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential