How this calculation is done i'am confused i am getting an answer 14 ??

#include<iostream>
#include<conio.h>
using namespace std;main()
{
int a=5;
int d;
d=++a + ++a;
cout<<d;
getch();
}

Recommended Answers

All 4 Replies

This might shed a little light on it ...

a = 5;
cout << a << "  " << ++a << "  " << ++a << '\n';

Think about it. ++a can't be added to something else until the ++ step is completed. So to finish this math my bet is the compiler completed the increments first to varible a and since it's only a pointer to a, a gets incremented twice before the final a + a is computed.

The compiler has to serialize the operations to something like:
a++;a++; d = a + a;
Which is 14.

Now you could get other answers by writing:
d = a++; d+=a++;
d = 2 * a++;

The moral is that writing code that depends on order of evaluation is a bad programming practice in any language.

actually first ++a is incrementing two times and during first increment it is asigned to 6 during second 7
and now the values is 7 for both a therefore the op is 7+7

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.