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

前端 未结 21 2065
伪装坚强ぢ
伪装坚强ぢ 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:12

    i++ and ++i

    This little code may help to visualize the difference from a different angle than the already posted answers:

    int i = 10, j = 10;
      
    printf ("i is %i \n", i);
    printf ("i++ is %i \n", i++);
    printf ("i is %i \n\n", i);
      
    printf ("j is %i \n", j);
    printf ("++j is %i \n", ++j);
    printf ("j is %i \n", j);
    

    The outcome is:

    //Remember that the values are i = 10, and j = 10
    
    i is 10 
    i++ is 10     //Assigns (print out), then increments
    i is 11 
    
    j is 10 
    ++j is 11    //Increments, then assigns (print out)
    j is 11 
    

    Pay attention to the before and after situations.

    for loop

    As for which one of them should be used in an incrementation block of a for loop, I think that the best we can do to make a decision is use a good example:

    int i, j;
    
    for (i = 0; i <= 3; i++)
        printf (" > iteration #%i", i);
    
    printf ("\n");
    
    for (j = 0; j <= 3; ++j)
        printf (" > iteration #%i", j);
    

    The outcome is:

    > iteration #0 > iteration #1 > iteration #2 > iteration #3
    > iteration #0 > iteration #1 > iteration #2 > iteration #3 
    

    I don't know about you, but I don't see any difference in its usage, at least in a for loop.

提交回复
热议问题