Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
/*on dev-cpp output=10
 visual c++ output=12
 why*/
#include<stdio.h>
#include<conio.h>
int main()
{
   int i,j;
   i=1;
   j=(++i)+(++i)+(++i);
   printf("%d",j);
   getch();
}


[edit]Code block added, HTML encoded - OriginalGriff[/edit]
Posted
Updated 17-Mar-13 4:34am
v2
Comments
nv3 17-Mar-13 11:03am    
There is an old saying: Crap in - crap out. I admit, OriginalGriff's explanation is more detailed :-)

It seems like the compilers handle it differently. Let's divide the statement and, try to figure it out.


First, you use the Prefix Increment Operator - which means that the increment operation should occur before the use of the value of i. But, how much before?


It seems like the first compiler increments the values directly before they are used. So, as we have two + operators, the first two increments are performed before the first + operator and the third increment is performed before the second + operator. What gives us: 3 + 3 + 4 = 10.


The second compiler performs the whole of the increments at the beginning of the statement. What gives us: 4 + 4 + 4 = 12.

 
Share this answer
 
v2
Comments
Sagar Srivastava 18-Mar-13 12:36pm    
but would you reply as answer if someone asks you
Sagar Srivastava 18-Mar-13 12:53pm    
i think it is because ambiguity in parse tree generated at time of symentic analysis .Bcaz that'only the place where this fault can occur as here only the exp is converted into preorder or postorder ........
The difference is because the specification does not formally say when the pre-increment should occur: the compiler can decide for itself whether it wants to do the pre-increment immediately before the use or at the beginning of the statement, to the benefit of it's execution module.
Clearly, the two compilers have different ideas of how to do it!

You really shouldn't do that - divide it into a couple of lines and let the copiler sort out any optimisations. It is not clear to read that exactly what you should get - one school of thought could be that it "should" be:
2 + 3 + 4 = 9

not 12 or 10!
 
Share this answer
 
Comments
Matthew Faithfull 17-Mar-13 11:28am    
That must be the school I went to. 5 from me.
Sagar Srivastava 18-Mar-13 12:56pm    
yes i also think so! Please ask this to others....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900