Cannot understand for loop with two variables [duplicate]

我与影子孤独终老i 提交于 2019-12-01 18:19:55

for(i=0,j=0;i<3,j<2;i++,j++)

is equivalent to

for(i=0,j=0;j<2;i++,j++)

The comma expression takes on the value of the last expression.

Whichever condition is first, will be disregarded, and the second one will be used only.

The for loop consists of:

for(START_STATEMENT; CONDITION_EXPRESSION, LOOP_EXPRESSION) BODY_BLOCK

Where:

  • START_STATEMENT is any single statement, which may include variable declaration. If you want to declare 2 variables, you can write int i=0, j=0, but not int i=0; int j=0 because the latter are actually 2 statements. Also node, that variable declaration is a part of statement, but cannot be a part of (sub) expression. That is why int i=0, int j=0 would also be incorrect.

  • CONDITION_EXPRESSION is any single expression that evaluates to a boolean value. In your case you are using a coma operator which has the following semantics: A, B will do:

    • evaluate A (it will evaluate, not just ignore)
    • ditch the result of A
    • evaluate B
    • return B as the result

    In your case: i<3,j<2 you are comparing i<3, you are just ignoring the result of this comparison.

    Comma expressions are useful when the instructions have some side effects, beyond just returning a value. Common cases are: variable increment/decrement or assignment operator.

  • LOOP_EXPRESSION is any single expression that does not have to evaluate to anything. Here you are using the comma expression again, ignoring the result of the left-hand-side. In this case however, you are not using the result anyway, and just using the ++ side effect - which is to increment the values of your variables.

  • BODY_BLOCK is either a single statement or a block, encapsulated with curly braces.

The above for can be compared to:

{
    START_STATEMENT;
    while(EXPRESSION) {
        BODY_BLOCK;
        LOOP_EXPRESSION;
    }
}

The c complier always used second condition.

therefore j<2 is used.

use this for loop

      for(i=0,j=0;j<10;i++,j++)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!