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

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

    The Main Difference is

    • i++ Post(After Increment) and
    • ++i Pre (Before Increment)

      • post if i =1 the loop increments like 1,2,3,4,n
      • pre if i =1 the loop increments like 2,3,4,5,n
    0 讨论(0)
  • 2020-11-21 06:30

    Shortly:

    ++i and i++ works same if you are not writing them in a function. If you use something like function(i++) or function(++i) you can see the difference.

    function(++i) says first increment i by 1, after that put this i into the function with new value.

    function(i++) says put first i into the function after that increment i by 1.

    int i=4;
    printf("%d\n",pow(++i,2));//it prints 25 and i is 5 now
    i=4;
    printf("%d",pow(i++,2));//it prints 16 i is 5 now
    
    0 讨论(0)
  • 2020-11-21 06:32
    • ++i will increment the value of i, and then return the incremented value.

       i = 1;
       j = ++i;
       (i is 2, j is 2)
      
    • i++ will increment the value of i, but return the original value that i held before being incremented.

       i = 1;
       j = i++;
       (i is 2, j is 1)
      

    For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R.

    In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.

    There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.

    The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C?

    As @OnFreund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.

    0 讨论(0)
提交回复
热议问题