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

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

    i++ is known as Post Increment whereas ++i is called Pre Increment.

    i++

    i++ is post increment because it increments i's value by 1 after the operation is over.

    Lets see the following example:

    int i = 1, j;
    j = i++;
    

    Here value of j = 1 but i = 2. Here value of i will be assigned to j first then i will be incremented.

    ++i

    ++i is pre increment because it increments i's value by 1 before the operation. It means j = i; will execute after i++.

    Lets see the following example:

    int i = 1, j;
    j = ++i;
    

    Here value of j = 2 but i = 2. Here value of i will be assigned to j after the i incremention of i. Similarly ++i will be executed before j=i;.

    For your question which should be used in the incrementation block of a for loop? the answer is, you can use any one.. doesn't matter. It will execute your for loop same no. of times.

    for(i=0; i<5; i++)
       printf("%d ",i);
    

    And

    for(i=0; i<5; ++i)
       printf("%d ",i);
    

    Both the loops will produce same output. ie 0 1 2 3 4.

    It only matters where you are using it.

    for(i = 0; i<5;)
        printf("%d ",++i);
    

    In this case output will be 1 2 3 4 5.

提交回复
热议问题