You are here:

C++/pre & Post increment

Advertisement


Question
Sir, 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.

Answer
Hi 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joydeep Bhattacharya

Expertise

TSR, Socket and Very Complex Mathematical Problem

Experience

Worked on many OOP projects with design patterns

Organizations
http://www.scodz.com

Publications
http://www.scodz.com

Education/Credentials
Master of Computer Applications

Awards and Honors
Being a proud owner of a website of programming called http://www.scodz.com

Past/Present Clients
http://www.funforu.com http://www.dhoondho.com http://analysingc.50webs.com

©2016 About.com. All rights reserved.