-1

Ruby's for/in loop can have many statement:

for a in 1..2 do
  expression 1
  expression 2
  ..
end

But it seems for loop in C can only have one:

for (a = 0; a < 10; a ++) expression 1;

Is there any way to make multiply statement in the for loop in C?

4

3 回答 3

6

Yes, formally speaking all loop statements in C take only one statement as the loop body. The same is true for branching statements (like if) and virtually all other statements in C.

However, that one statement can be a compound one. A compound statement begins with {, ends with } and contains an arbitrary number of nested statements inside. (Note that there's no ; at the end of compound statement.)

于 2012-07-22T04:34:21.513 回答
2

Use braces for the body of the loop:

for (a = 0; a < 10; a++) 
{
    doSomething();
    doSomethingElse();
}

This concept extends to other things, like if, as well. This should be mentioned right alongside the if and for themselves in any book, etc.

于 2012-07-22T04:31:24.660 回答
2

You need to learn C syntax. You put them in a block

for (...) {
   expression 1;
   expression 2;
}
于 2012-07-22T04:31:50.773 回答