質問

Are the following two code blocks exactly the same and achieve the same thing?It displays the same thing when I run the program,but I would appreciate some rigorous explanation.

for(i=1;i<=10;i++)
{
printf("%d\n",i);
}

and

for(i=1;i<=10;printf("%d\n",i),i++);

The for loop expects valid C statements as arguments,doesn't it? But even though I have verified on StackOverflow that statements like x+=4,y=x*2; are safe as the comma acts as sequence points here, is the same truth for the statement printf("%d\n",i),i++) passed as argument in the for loop above?

And if yes, please bother to answer the minor question that arise from it:

  • Does the comma act as sequence points in a statement involving many comma separated

    function calls as below:

    printf("Enter number\n"),scanf("%d",&number),printf("You entered %d",number);

役に立ちましたか?

解決

This is perfectly valid and both statements are equal to the compiler. For the reader the second is almost unreadable, so that is the only difference that is. It makes very little sense to use the second format.

A sequence point is introduced by the comma operator.

Reference:

6.5.17 Comma operator

Para 2:

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.114)

他のヒント

The answer is in 6.8.5.3 of the C standard:

1774 The statement

    for ( clause-1 ; expression-2 ; expression-3 ) statement

behaves as follows:

1775 The expression >expression-2 is the controlling expression that is evaluated before each execution of the loop body.

1776 The expression expression-3 is evaluated as a void expression after each execution of the loop body.

1777 If clause-1 is a declaration, the scope of any identifiers it declares is the remainder of the declaration and the entire loop, including the other two expressions;

1778 it is reached in the order of execution before the first evaluation of the controlling expression.

1779 If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.134)

1780 Both clause-1 and expression-3 can be omitted.

1781 An omitted expression-2 is replaced by a nonzero constant.

There is a sequence point established between execution of the printf statement and then the incrementing of i. The printf statement and i is expression-3 in this case, not a conditional, so the statement is valid though not best practice.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top