C++/pre & Post increment
Expert: Joydeep Bhattacharya - 8/1/2007
QuestionSir, Please read the question.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,add;
a=5;
add = (++a)+(++a);
cout<<add;
getch();
}
According to me the answer should be 13. But compiler gives 14. Why is it so.
AnswerHi Kuldeep
Firstly don't call me sir and secondly I am here to help you my friend.
Okies lets diagonise your problem
to you the statement should evaluate to
add = 7 + 6 = 13 // right
Now tell me something a is a variable is it capable of holding 2 values at the same time either of 6 or 7 can be stored inside a now whats the latest value of a its 7 right
so add = 7 + 7 = 14;
You can try it out with different combination and you will see that in everycase its the same
check this
add = (++a) + (a) + (a++) = 6 + 6 + 6 = 18 and not 7 + 6 + 5 = 18.
another one add = (++a) + (++a) + (++a) + (++a) in all the cases it will turn out to be no of expression * latest value of variable.
For many such topics like this you can refer to my personal website at
http://www.scodz.com
Please don't hesitate t get back to me in case of any problem
regards
Joydeep Bhattacharya
http://www.scodz.com