Why postfixed has higher precedence than prefixed? [duplicate] - c

This question already has answers here:
What is the difference between pre-increment and post-increment in the cycle (for/while)?
(8 answers)
Closed 5 years ago.
Case 1:
int i = 10;
int j = i++;
Here, first the value of i is assigned to j and than i is increased by 1.
Case 2:
int i = 10;
int j = ++i;
Here, first i is increased by 1 and than it is assigned to j.
So, If the operation of increment is done first in the prefixed form, then why postfixed has higher precedence than prefixed?

This has nothing to do with precedence.(here) In pre-increment the value that is assigned is the value before the side effect takes place.
For pre increment it will be the value after the side effect.
int i = 10;
int j = i++;
Before incrementing value of i is 10. So j=10 after these 2 statements are executed.
int i = 10;
int j = ++i;
Here the value will be 11. because incremenet is done first and then it is assigned.

Linux manual page of operator define as same priority for both pre/post increment.
! ~ ++ -- + - (type) * & sizeof right to left
post increment rule is first assigned and then increment
int j = i++;// here first whatever i value is there that will be assigned to j
Pre increment rule is first increment and then assign
int j = ++i;//++i itself will change i value & then modfied value will assign to j.
for e.g consider below example
#include<stdio.h>
int main()
{
int x = 10;
int *p = &x;// assume p holds 0x100
printf("x = %d *p = %d p = %p\n",x,*p,p);
++*p++;
/** in above statement ++ and * having same precedence,then you should check assocaitivity which is R to L
So start solving from Right to Left, whichever operator came first , solve that one first
first *p++ came , again solve p++ first, which is post increment,so address will be same
*0x100 means = 10
now ++10 means = 11
**/
printf("x = %d *p = %d p = %p\n",x,*p,p);
}

Related

Dereferencing a post-incremented pointer vs incrementing pointer and then dereferencing? [duplicate]

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?
++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.
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.
Let’s see the following example:
int i = 1, j;
j = i++;
Here value of j = 1, but i = 2. Here the value of i will be assigned to j first, and 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++.
Let’s see the following example:
int i = 1, j;
j = ++i;
Here the value of j = 2 but i = 2. Here the 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... It doesn't matter. It will execute your for loop same number 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 the same output. I.e., 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.
i++: In this scenario first the value is assigned and then increment happens.
++i: In this scenario first the increment is done and then value is assigned
Below is the image visualization and also here is a nice practical video which demonstrates the same.
++i increments the value, then returns it.
i++ returns the value, and then increments it.
It's a subtle difference.
For a for loop, use ++i, as it's slightly faster. i++ will create an extra copy that just gets thrown away.
Please don't worry about the "efficiency" (speed, really) of which one is faster. We have compilers these days that take care of these things. Use whichever one makes sense to use, based on which more clearly shows your intent.
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<stdio.h>
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<stdio.h>
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=0
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, as well as (i++)*2 and (++i)*2) 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)
Efficiency
Pre-increment is always at least as efficient as post-increment: in fact post-increment usually involves keeping a copy of the previous value around and might add a little extra code.
As others have suggested, due to compiler optimisations many times they are equally efficient, probably a for loop lies within these cases.
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:
The reason ++i can be slightly faster than i++ is that i++ can require a local copy of the value of i before it gets incremented, while ++i never does. In some cases, some compilers will optimize it away if possible... but it's not always possible, and not all compilers do this.
I try not to rely too much on compilers optimizations, so I'd follow Ryan Fox's advice: when I can use both, I use ++i.
The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.
In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.
However, you should consider two main problems with the preceding logic.
Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.
In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.
In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.
This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."
++i: is pre-increment the other is post-increment.
i++: gets the element and then increments it.
++i: increments i and then returns the element.
Example:
int i = 0;
printf("i: %d\n", i);
printf("i++: %d\n", i++);
printf("++i: %d\n", ++i);
Output:
i: 0
i++: 0
++i: 2
++i (Prefix operation): Increments and then assigns the value
(eg): int i = 5, int b = ++i
In this case, 6 is assigned to b first and then increments to 7 and so on.
i++ (Postfix operation): Assigns and then increments the value
(eg): int i = 5, int b = i++
In this case, 5 is assigned to b first and then increments to 6 and so on.
Incase of for loop: i++ is mostly used because, normally we use the starting value of i before incrementing in for loop. But depending on your program logic it may vary.
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.
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int i;
int j;
Increment operators:
i = 1;
j = ++i; // i is now 2, j is also 2
j = i++; // i is now 3, j is 2
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
Pre-crement means increment on the same line. Post-increment means increment after the line executes.
int j = 0;
System.out.println(j); // 0
System.out.println(j++); // 0. post-increment. It means after this line executes j increments.
int k = 0;
System.out.println(k); // 0
System.out.println(++k); // 1. pre increment. It means it increments first and then the line executes
When it comes with OR, AND operators, it becomes more interesting.
int m = 0;
if((m == 0 || m++ == 0) && (m++ == 1)) { // False
// In the OR condition, if the first line is already true
// then the compiler doesn't check the rest. It is a
// technique of compiler optimization
System.out.println("post-increment " + m);
}
int n = 0;
if((n == 0 || n++ == 0) && (++n == 1)) { // True
System.out.println("pre-increment " + n); // 1
}
In Array
System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 };
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); // 12
jj = a[1]++; // 12
System.out.println(a[1]); // a[1] = 13
mm = a[1]; // 13
System.out.printf("\n%d %d %d\n", ii, jj, mm); // 12, 12, 13
for (int val: a) {
System.out.print(" " + val); // 55, 13, 15, 20, 25
}
In C++ post/pre-increment of pointer variable
#include <iostream>
using namespace std;
int main() {
int x = 10;
int* p = &x;
std::cout << "address = " << p <<"\n"; // Prints the address of x
std::cout << "address = " << p <<"\n"; // Prints (the address of x) + sizeof(int)
std::cout << "address = " << &x <<"\n"; // Prints the address of x
std::cout << "address = " << ++&x << "\n"; // Error. The reference can't reassign, because it is fixed (immutable).
}
I assume you understand the difference in semantics now (though honestly I wonder why
people ask 'what does operator X mean' questions on stack overflow rather than reading,
you know, a book or web tutorial or something.
But anyway, as far as which one to use, ignore questions of performance, which are
unlikely important even in C++. This is the principle you should use when deciding
which to use:
Say what you mean in code.
If you don't need the value-before-increment in your statement, don't use that form of the operator. It's a minor issue, but unless you are working with a style guide that bans one
version in favor of the other altogether (aka a bone-headed style guide), you should use
the form that most exactly expresses what you are trying to do.
QED, use the pre-increment version:
for (int i = 0; i != X; ++i) ...
The difference can be understood by this simple C++ code below:
int i, j, k, l;
i = 1; //initialize int i with 1
j = i+1; //add 1 with i and set that as the value of j. i is still 1
k = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1
l = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.
cout << i << ' ' << j << ' ' << k << ' '<< l << endl;
return 0;
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
In simple words the difference between both is in the steps take a look to the image below.
Example:
int i = 1;
int j = i++;
The j result is 1
int i = 1;
int j = ++i;
The j result is 2
Note: in both cases i values is 2
You can think of the internal conversion of that as multiple statements:
// case 1
i++;
/* you can think as,
* i;
* i= i+1;
*/
// case 2
++i;
/* you can think as,
* i = i+i;
* i;
*/
a=i++ means a contains the current i value.
a=++i means a contains the incremented i value.

In which cases i++ and ++i can refer to the same value? [duplicate]

This question already has answers here:
What is the difference between ++i and i++?
(20 answers)
Closed 9 years ago.
Why is i++ and ++i same in the following code?
#include <stdio.h>
int main()
{
int i=5;
while(1)
{
i++; /*replacing i++ by ++i also gives 6*/
printf("%d",i);
break;
}
return 0;
}
The output is 6. I learnt that the increment operator i++ has its value the current value of i and causes the stored value of i to be incremented.But i's value is displayed as 6 though the current value of i is 5. Replacing i++ by ++i also gives the same value 6. Why is i++ and ++i same in this case and why output is 6 though initial value is 5.
The order of execution is sequential.
i++ or for that matter ++i is a single instruction to be executed at that sequence point, with i's value not being used anywhere at that instruction, so it doesn't really matter.
If you do replace printf("%d",i); with printf("%d",i++); or printf("%d",++i); things will be much different.
EDIT: I also discovered something that is fairly useful to know. In C and C++, the prefix unary operator returns an lvalue, in contrast to the postfix unary operator, so if you want to, for example, decrement i twice, then
(i--)--; // is illegal
whereas
(--i)--; // is perfectly legal and works as intended.
Check out the answer I found at What is the difference between ++i and i++?
"++i will increment the value of i, and then return the incremented value."
"i++ will increment the value of i, but return the original value that i held before being incremented."
You don't use value which it returns, so it does not matter in your case.
It only changes what value will be set when used in a method.
With i++ you'll use i in the method, once done i will be increased.
With ++I first you increase the value and then you use it in the method.
i++ - add 1 to i returns the old value.
++i - add 1 to i, returns the new value.
In your case :
i++ - returns 5 and add 1 to i make i as 6. If you catch the
return value of i++ you can get the clear idea. because return will have the value 5.
++i - add 1 to i and make i as 6 then return i=6
Sample code:
#include <stdio.h>
int main()
{
int i=5;
while(1)
{
int post, pre;
post = i++;
printf("post : %d, i: %d\n", post, i);
i = 5;
pre = ++i;
printf("pre : %d, i: %d\n", pre, i);
break;
}
return 0;
}
Output:
post : 5, i: 6
pre : 6, i: 6
int i = 5;
i++; // implies i = i + 1 ==> 6
// Even ++i results the same
printf("%d",i); // Obviously it prints 6
If you don't assign the returned value to a variable or use it as an argument, the result is the exact same.
The primary difference between the two is that ++i increments the variable and only then assigns the value, while i++ assigns first and increments afterwards.

How to determine i+++--j in C

In C,
int i = 20;
int j = 5;
int k = i+++--j;
Why is k=24?
In my understanding, k = (i)++ + (--j) so it is (20 + 4)++ = 25.
OK. Here is a little programme I wrote for test, and yes the post increment is done after k is assigned.
#include <stdio.h>
int main()
{
int i = 20;
int k = i++;
printf("%d\n", k);
printf("%d\n", i);
return 0;
}
Output:
20
21
Could anyone tell me why vote down? I was unsure about this because I was a new commer to C.
C has a famous rule of maximal munch strategy.
From this rule:
i+++--j
is parsed as
(i++) + (--j)
(C99, 6.4p4) "If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token."
And of course the value of i++ is i and the value of --j is j - 1, so the value of i+++--j is 20 + 4 equal to 24.
Think of it as a greedy algorithm, it will take as many characters as possible, if they make sense.
Example:
i+ // good, keep going
i++ // good, keep going
i+++ // not good, start new token
+ // good, keep going
+- // not valid, start new token
- // good
-- // good
--j // valid
So:
int i = 20;
int j = 5;
int k = i++ + --j; // (20++) + (--5)
That is how it is grouped. The second part is pre and post increment.
i++ // post-increment, use the value first and then increment
--j // pre-increment, decrement first and then use the value
So you get:
int k = 20 + 4
// afterwards: i = 21 and j = 4
In my understanding, k = (i)++ + (--j)
Yes, that's it.
so it is (20 + 4)++ = 25.
No, it's 20 + 4 and so it is 24. (You can't increment a constant, nor does it make any sense, nor is there a second increment operator in the expression, so I really don't know where you got that idea). But otherwise your deduction is correct.
I agree with what others have said as far as parsing. By the way, when faced with questions such as this operator precedence can be very important. For C, this site has a list of operators and their precedence.
The value of k is determined by the operators precedence.
The difference bitween n = i++ and n = ++i, is that in the first the value is of i is assigned to n before the incrementation, but in the last the value of i is assigned to n after the incrementation.
In the case of k = i++ + --j. the operations are processed in this order:
1) decrement j by 1 (j = j-1)
2) assign i + j to k (k = i + j)
3) increment i by 1 (i = i + 1)

Is ++ the same as += 1 for pointers?

I'd like to refactor some old C code of mine, and I was curious if I can replace all ptr++ with ptr += 1 where ptris some pointer, without changing any behavior. Here's an example of what I mean, from K&R Section 5.3:
/* strlen: return length of string s*/
int strlen(char *s)
{
int n;
for (n = 0; *s != '\0'; s++)
n++;
return n;
}
When I replace the s++ with s += 1, I get the same results, but I'm wondering if this will be the case for all types. I also did a test for ints:
int size = 10;
int *int_array = (int*)calloc(size, sizeof(int));
for (int i = 0; i < size; i++)
int_array[i] = i;
for (int i = 0; i < size; i++) {
printf("*int_array = %d\n", i, *int_array);
int_array++;
}
If I replace the line int_array++; with int_array += 1;, I get the same result.
After thinking about this some more, I realize there could be a problem if the value is used in an expression. Would it be safer I just moved the increment onto another line like so:
int a = 5;
int b = a++;
would become:
int a = 5;
int b = a;
a += 1;
Conclusion
What I thought could be a problem, incrementing pointers of different types, is not a problem. See #bdonlan's response for the reason why.
This doesn't mean that you can replace all x++ with x += 1 and expect the same behavior. You can, however, replace ++x with (x += 1) safely, since they are equivalent.
a += 1 is equivalent to ++a (C99 §6.5.3.1/2). In a line like int b = a++; this means it is not equivalent to a++; a++ would return the old value of a, while a += 1 returns the new value.
Note that if you don't use the result of a++ (ie, you have a statement containing just a++;), then they are effectively identical.
Also, note that _all pointer arithmetic is done in increments of the pointed-to type's size (§6.5.6/8). This means that:
ptr = ptr + x;
is equivalent to:
ptr = (ptr_type *)( (char *)ptr + x * sizeof(*ptr) );
This is the same whether you use +, ++, +=, or [] (p[x] is exactly equivalent to *(p + x); you can even do things like 4["Hello"] because of this).
++ and -- is defined in terms of arithmetic for built-in types. The behavior will be the same, other than postfix returning the old value.
It's a good question. The answer is yes, you can do that -- no matter how you do it, incrementing a pointer adds sizeof(the type that the pointer points to) to the pointer. As other answers indicate, you do need to be careful that you don't depend on when the increment happens, i.e. a++ and ++a have different effect, but a eventually ends up with the same value.
A question is: why do you want to change all your code from a++ to a+=1? Using the post-increment operator with pointers is something that should be easily understood by any C programmer, so it's hard to understand why you'd make that change.

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

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?
++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.
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.
Let’s see the following example:
int i = 1, j;
j = i++;
Here value of j = 1, but i = 2. Here the value of i will be assigned to j first, and 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++.
Let’s see the following example:
int i = 1, j;
j = ++i;
Here the value of j = 2 but i = 2. Here the 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... It doesn't matter. It will execute your for loop same number 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 the same output. I.e., 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.
i++: In this scenario first the value is assigned and then increment happens.
++i: In this scenario first the increment is done and then value is assigned
Below is the image visualization and also here is a nice practical video which demonstrates the same.
++i increments the value, then returns it.
i++ returns the value, and then increments it.
It's a subtle difference.
For a for loop, use ++i, as it's slightly faster. i++ will create an extra copy that just gets thrown away.
Please don't worry about the "efficiency" (speed, really) of which one is faster. We have compilers these days that take care of these things. Use whichever one makes sense to use, based on which more clearly shows your intent.
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<stdio.h>
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<stdio.h>
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=0
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, as well as (i++)*2 and (++i)*2) 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)
Efficiency
Pre-increment is always at least as efficient as post-increment: in fact post-increment usually involves keeping a copy of the previous value around and might add a little extra code.
As others have suggested, due to compiler optimisations many times they are equally efficient, probably a for loop lies within these cases.
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:
The reason ++i can be slightly faster than i++ is that i++ can require a local copy of the value of i before it gets incremented, while ++i never does. In some cases, some compilers will optimize it away if possible... but it's not always possible, and not all compilers do this.
I try not to rely too much on compilers optimizations, so I'd follow Ryan Fox's advice: when I can use both, I use ++i.
The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.
In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.
However, you should consider two main problems with the preceding logic.
Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.
In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.
In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.
This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."
++i: is pre-increment the other is post-increment.
i++: gets the element and then increments it.
++i: increments i and then returns the element.
Example:
int i = 0;
printf("i: %d\n", i);
printf("i++: %d\n", i++);
printf("++i: %d\n", ++i);
Output:
i: 0
i++: 0
++i: 2
++i (Prefix operation): Increments and then assigns the value
(eg): int i = 5, int b = ++i
In this case, 6 is assigned to b first and then increments to 7 and so on.
i++ (Postfix operation): Assigns and then increments the value
(eg): int i = 5, int b = i++
In this case, 5 is assigned to b first and then increments to 6 and so on.
Incase of for loop: i++ is mostly used because, normally we use the starting value of i before incrementing in for loop. But depending on your program logic it may vary.
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.
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int i;
int j;
Increment operators:
i = 1;
j = ++i; // i is now 2, j is also 2
j = i++; // i is now 3, j is 2
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
Pre-crement means increment on the same line. Post-increment means increment after the line executes.
int j = 0;
System.out.println(j); // 0
System.out.println(j++); // 0. post-increment. It means after this line executes j increments.
int k = 0;
System.out.println(k); // 0
System.out.println(++k); // 1. pre increment. It means it increments first and then the line executes
When it comes with OR, AND operators, it becomes more interesting.
int m = 0;
if((m == 0 || m++ == 0) && (m++ == 1)) { // False
// In the OR condition, if the first line is already true
// then the compiler doesn't check the rest. It is a
// technique of compiler optimization
System.out.println("post-increment " + m);
}
int n = 0;
if((n == 0 || n++ == 0) && (++n == 1)) { // True
System.out.println("pre-increment " + n); // 1
}
In Array
System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 };
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); // 12
jj = a[1]++; // 12
System.out.println(a[1]); // a[1] = 13
mm = a[1]; // 13
System.out.printf("\n%d %d %d\n", ii, jj, mm); // 12, 12, 13
for (int val: a) {
System.out.print(" " + val); // 55, 13, 15, 20, 25
}
In C++ post/pre-increment of pointer variable
#include <iostream>
using namespace std;
int main() {
int x = 10;
int* p = &x;
std::cout << "address = " << p <<"\n"; // Prints the address of x
std::cout << "address = " << p <<"\n"; // Prints (the address of x) + sizeof(int)
std::cout << "address = " << &x <<"\n"; // Prints the address of x
std::cout << "address = " << ++&x << "\n"; // Error. The reference can't reassign, because it is fixed (immutable).
}
I assume you understand the difference in semantics now (though honestly I wonder why
people ask 'what does operator X mean' questions on stack overflow rather than reading,
you know, a book or web tutorial or something.
But anyway, as far as which one to use, ignore questions of performance, which are
unlikely important even in C++. This is the principle you should use when deciding
which to use:
Say what you mean in code.
If you don't need the value-before-increment in your statement, don't use that form of the operator. It's a minor issue, but unless you are working with a style guide that bans one
version in favor of the other altogether (aka a bone-headed style guide), you should use
the form that most exactly expresses what you are trying to do.
QED, use the pre-increment version:
for (int i = 0; i != X; ++i) ...
The difference can be understood by this simple C++ code below:
int i, j, k, l;
i = 1; //initialize int i with 1
j = i+1; //add 1 with i and set that as the value of j. i is still 1
k = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1
l = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.
cout << i << ' ' << j << ' ' << k << ' '<< l << endl;
return 0;
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
In simple words the difference between both is in the steps take a look to the image below.
Example:
int i = 1;
int j = i++;
The j result is 1
int i = 1;
int j = ++i;
The j result is 2
Note: in both cases i values is 2
You can think of the internal conversion of that as multiple statements:
// case 1
i++;
/* you can think as,
* i;
* i= i+1;
*/
// case 2
++i;
/* you can think as,
* i = i+i;
* i;
*/
a=i++ means a contains the current i value.
a=++i means a contains the incremented i value.

Resources