What's allowed in the header of a for loop?
In C#, I've seen some strange and complex logic in the headers of loops.
What is/isn't possible in the h开发者_高级运维eader of a for loop? Is it possible to have more than one incrementor/variable?
Thanks
Is it possible to have more than one incrementor/variable?
Yes, it is possible. That is, this is perfectly legal:
// reverse b into a
for (int i = 0, j = n - 1; i < n; i++, j--) {
a[i] = b[j]
}
What is/isn't possible in the header of a
for
loop?
That is exactly what the grammar will tell you. Here is the grammar for a for
statement in C#:
for-statement:
for(for-initializer_opt; for-condition_opt; for-iterator_opt)
embedded-statement
for-initializer:
local-variable-declaration
statement-expression-list
for-condition:
boolean-expression
for-iterator:
statement-expression-list
statement-expression-list:
statement-expression
statement-expression-list, statement-expression
Note that both the for-initializer
and the for-iterator
allow compound statements via statement-expression-list
. See §8.8.3 of the language specification for addtional details. You'll probably also want to visit §8.5.1 of the specification for exactly what local-variable-declaration
entails (hint: int i = 0, j = n - 1, k = 42
is legal but int i = 0, j = n - 1, long k = 42
is not).
The ECMA-334 C# Language Specification
C# Language Specifications
精彩评论