Code: #include<stdio.h> #include<conio.h> main() { int a=5; int b=(a)+(++a)+(++a); printf("%d",b); getch(); } // [COLOR=Blue]HERE THE OUTPUT COMES AS[/COLOR] [COLOR=DarkOrange]21[/COLOR]!! #include<stdio.h> #include<conio.h> main() { int a=5; int b=0; b=(a)+(++a)+(++a); printf("%d",b); getch(); } // HERE THE OUTPUT COMES AS 19!! WHY THIS VARIANCE IN OUTPUT IS OCCURING?? - PLEASE HELP!!!
Statements such as this: int b=(a)+(++a)+(++a); result in undefined behavior. Read up on sequence points. Also, read the "Before you make a query" thread, see the upper right corner of this page. By not using code tags, you are being rude to those you are asking for help.
It doesn't matter what you get; that's the point. The results are undefined. The compiler can do anything it likes. What it chooses to do is allowed to change with the next version. The standard does define the order of the additions, but it doesn't define the order of evaluating the expressions PRIOR TO the additions. As I said, read about sequence points. Playing with undefined operation may seem like fun but it's totally wasted time, since you can't depend upon your results being repeatable from compiler to compiler. Code correctness is not determined by what the compiler does; it's determined by the standards. Compiler correctness is determined by the standard. In the event the standard chooses not to define something (hardware implementations may make it infeasible to define some operations), the compiler writer may do as he wishes. And change what he does whenever he wishes.