0

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();
}
4
Contributors
4
Replies
50
Views
2 Years
Discussion Span
Last Post by shajin c l
0

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++;

3

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

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.