The for statement has the general syntax
for ([init]; [test]; [inc]) statement
and performs the following steps:
If there is no
inside the statement, the inc expression (or the
statement) must affect
the value of the test expression, or test itself must
change during evaluation in order to avoid an endless loop.
- If an initializing expression init is present, it is executed.
- If a test expression is present, it is executed. If the result
is nonzero (or if there is no test expression at all), the
statement is executed.
- If an inc expression is present, it is executed.
- Finally control returns to step 2.
The initializing expression init normally initializes one or more
loop counters. It may also define a new variable as a loop counter.
The scope of such a variable is valid until the end of the active block.
string s = "Trust no one!";
int sum = 0;
for (int i = 0; s[i]; ++i)
sum += s[i]; // sums up the characters in s
Copyright © 2005 CadSoft Computer GmbH