C: What is the difference between ++i and i++?

前端 未结 21 2071
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 06:04

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?

21条回答
  •  终归单人心
    2020-11-21 06:21

    The only difference is the order of operations between the increment of the variable and the value the operator returns.

    This code and its output explains the the difference:

    #include
    
    int main(int argc, char* argv[])
    {
      unsigned int i=0, a;
      printf("i initial value: %d; ", i);
      a = i++;
      printf("value returned by i++: %d, i after: %d\n", a, i);
      i=0;
      printf("i initial value: %d; ", i);
      a = ++i;
      printf(" value returned by ++i: %d, i after: %d\n",a, i);
    }
    

    The output is:

    i initial value: 0; value returned by i++: 0, i after: 1
    i initial value: 0;  value returned by ++i: 1, i after: 1
    

    So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.

    Another example:

    #include
    
    int main ()
      int i=0;
      int a = i++*2;
      printf("i=0, i++*2=%d\n", a);
      i=0;
      a = ++i * 2;
      printf("i=0, ++i*2=%d\n", a);
      i=0;
      a = (++i) * 2;
      printf("i=0, (++i)*2=%d\n", a);
      i=0;
      a = (++i) * 2;
      printf("i=0, (++i)*2=%d\n", a);
      return 0;
    }
    

    Output:

    i=0, i++*2=0
    i=0, ++i*2=2
    i=0, (++i)*2=2
    i=0, (++i)*2=2
    

    Many times there is no difference

    Differences are clear when the returned value is assigned to another variable or when the increment is performed in concatenation with other operations where operations precedence is applied (i++*2 is different from ++i*2, but (i++)*2 and (++i)*2 returns the same value) in many cases they are interchangeable. A classical example is the for loop syntax:

    for(int i=0; i<10; i++)
    

    has the same effect of

    for(int i=0; i<10; ++i)
    

    Rule to remember

    To not make any confusion between the two operators I adopted this rule:

    Associate the position of the operator ++ with respect to the variable i to the order of the ++ operation with respect to the assignment

    Said in other words:

    • ++ before i means incrementation must be carried out before assignment;
    • ++ after i means incrementation must be carried out after assignment:

提交回复
热议问题