+ 2
A++ and ++a.
I'm confused. what is real difference between them. I tried Cout<<a++<<++a ; output was 6 7. when done in single statement. but... Cout<<a++; Cout<<++a; this gave output 5 6. why is it so.
3 Answers
+ 1
a++ is like, during the expression, it remains 'a', but right after it finds a semicolon, it evaluates to a = a+1..
say, in below example,
int x,a=3;
x = (a++) + (a++);
cout<<x<<a
output will be 6 and 5.
this is because, while evaluating the expression of x, 'a' is still 3. and hence, it is 3+3.
but right after the expression, the compiler remembers that there were two instances of a++ and hence, a is incremented twice. so, it turns from 3 to 5.
However, if it is pre incremente, it first evaluates the value of a and then proceeds with the rest.
say, if a=3 and,
x=(++a) + (++a);
then, first a gets incremented to 4, then again to 5 and now, it proceeds to evaluate, x = 4 + 5 = 9
and a remains to be 5.
0
I forgot to mention initially a=5;
0
thanks... it was really helpful