Difference between i++ and ++i
i = 1;
j = ++i;
printf("i = %d, j = %d", i, j)
// Output =>
i = 2, j = 2
i = 1;
j = i++;
printf("i = %d, j = %d", i, j)
// Output =>
i = 2, j = 1
Look, in this example j is not incremented, j is the original i's value.
When we've to use i++ or ++i
This is a question I've brought from many people, when we've use i++ or ++i.You've seen the difference of them. Now it's your choice. You can use any of them i++ or ++i. For a for loop, they works just same.
But as a programmer or in common programming ++i is always better than i++. ++i never goes wrong. See the performance issue part.
Performance issue i++ vs ++i
First need to tell for a small project theirs no difference between i++ or ++i.But potentially i++ could be slower than ++i , Because i++ will create an extra copy and that's need a memory, which is not by ++i.
Why: See the example again
i = 1; //1
++i; // 2
i = 1; //1
i++; // 1
Look here,
- In first case, there is no temporary value to store, it just print the incremented value
- In second case i++, it's not printing the incremented value. It's store the value in another temp file. That is really unnecessary and takes memory.
And another thing, though i++ needs a temp variable, it's not any hard task for our computer today and in real life basically they are the same.
both the i++ or ++i containing file create the same object file and theirs no difference.
There is no compiler difference today between ++i or i++.
See a compiler object both i++ and ++i
After generating an assembler of both ++i and i++ by this way,$ gcc -c i++.c ++i.c
$ gcc -S i++.c ++i.c
Assembler output of both are the same, like -
$ md5 i++.s ++i.s
MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e
MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e
$ md5 *.o
MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22
MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22
But it's obviously better to use ++i over i++.
Conclusion on ++i and i++:
Since it seems that i++ take a local variable copy and ++i don't, in today's computer can manipulate them same manner and theirs really don't performance issue.Hopefully, your conflict has cleared now about ++i or i++. You can use both depending on your needs.