Frage

Is it possible, according to the C89/C90 standard, to insert a block of code into the increment clause of a for statement?

For instance:

int x = 0, y;
for (y = 0; x + y < SOME_CONST; { y++; x++; })
{
    //code
}

instead of:

int x = 0, y;
for (y = 0; x + y < SOME_CONST; x++)
{
    y++;
    //code
}

All I know so far is that it won't work with the Microsoft C/C++ compiler, but what does the standard say?

And what about the initialization clause? Can I put a block of code in there?

War es hilfreich?

Lösung

The grammar for the for iteration-statement in C89 is

for (expressionopt; expressionopt; expressionopt) statement

Where expressionopt is either an expression or omitted: e.g. for (;;); is valid C. Simply put, {y++; x++;} is not an expressionopt but rather it's a statement. So it can't be used in the for loop. Something like x++, y++ is an expression with a value of the previous value of y so it can be.

In later versions of C, the first expressionopt is enhanced to a clause which permits code like for (int a.... But this is not valid in C89. But code like for (x = 1, y = 2; is valid since x = 1, y = 2 is an expression.

Andere Tipps

You can't do a "block" of code, but you can have comma separated statements. For example,

int x = 0, y;
for (y = 0; x + y < SOME_CONST; y++, x++ )
{
    //code
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top