i++ and ++i
Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)
cscgal
The Queen of DaniWeb
19,424 posts since Feb 2002
Reputation Points: 1,474
Solved Threads: 230
Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)
//Lets declare i, and set it equal to 4.
int i = 4;
//Now say their is a function nammed goFetch(int), and we wanted to pass an increment of i to it
//i = 4 before this code gets touched, the value 4 would be passed, and then i would become 5
goFetch(i++);
//i = 4 before this code gets touched, i gets incrimented before anything else (and becomes 5), and the value 5 would be passed
goFetch(++i);
So, ++i means to incriment first then give the incrimented value, and i++ means to give the original value, then incriment.
Tekmaven
Software Architect
1,274 posts since Feb 2002
Reputation Points: 322
Solved Threads: 28
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
that is simple
++i means pre increment.
i++ means post increment.
consider the programme
..
main()
{
int a=7;
printf("%d\t%d\t%d\t%d\t",++a,a++,++a,a++);
printf("%d\n"a);
getch();
}
the ot put is
10 10 8 8
11
a++ here increments the value and shows it but ++a increments the value and gives it for next operation.ie ++a increments but not show the value.
You picked the worst example you could -- it is purely undefined behavior. http://www.eskimo.com/~scs/C-faq/q3.2.html
if you are using void main()function at the beginning do not use return 0 at the end.If you are using void main(), and are on a hosted implementation, you are incorrect. (It seems to me I may have mentioned this already?)
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Can someone please explain to me the difference between ++i and i++ when written as part of an expression (i.e. within loops and if statements) ? Thanks :)
Simply ++i increments i first and then does any computation in the loop ...
and i++ first does the computation and then increments i.
nanosani
Unauthenticated Liar
1,830 posts since Jul 2004
Reputation Points: 45
Solved Threads: 56
One thing that is good to remember is that ++i is returned by reference while i++ is returned by value.
Never heard that one before.:-O
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343