Tuesday, July 28, 2009

A Programming paradox ..It would be non-trivial to think why this discrepancy exists between the two languages

Check these two programmes out, both exactly the same. One written in Java , the other in C. can anyone truly explain the discrepancy and the reason behind it.


(this isnt really as easy as it seems, serious answers requested.. please)





//java code starts


public class IncrementTest{


public static void main (String args[]){


int i = 5;


int j = 5;


i = ++i + ++i; //the output here is 13


j = j++ + j++; //the output here is 11


System.out.println("New value is: "+i);


System.out.println("New value is: "+j);


}


}








______________________________________...


//C code


#include%26lt;stdio.h%26gt;





int main(){


int i =5;


int j = 5;


i = ++i + ++i; //the output here is 14


j = j++ + j++; //the output here is 12





printf("New value of i is: %d \n",i);


printf("New value of j is: %d \n",j);


fflush(stdout);





return 0 ;


}








both programs give different output, any thoughts ?

A Programming paradox ..It would be non-trivial to think why this discrepancy exists between the two languages
I don't know enough of Java to say for certain how it works (but I can hazard a guess from your example). But I certainly can explain the C program. Understanding why the code does what it does in C requires you to understand (a) order of operator evaluation and (b) the danger of postfix.





In the example for i:


++i takes precedence over the i + i operation. Hence, we have ++i happening twice, so i becomes 7. Then the + operation is evaluated, and we have 7+7 =14.





In the example of j:


The actual result is undefined, although in your case it happens to be 12. That's because you did j++ instead of ++j. j++ means j is incremented after j is evaluated. The problem is *when* that increment operation will occur. It could occur right after the entire expression is evaluated, or only after a certain sequence point, or right after j is evaluated. __It's_not_defined__. See also http://c-faq.com/expr/ieqiplusplus.html and http://c-faq.com/expr/seqpoints.html to understand the traps in using postfix notation.





In any case, there is no paradox here. This is a solid example of why people need to understand how operators and postfix/prefix works in a programming language.
Reply:I think that it is a compilation premises issue. C standard was made up of compiler vendors, whose marketing depends heavily on performance, and so the language definition goes out of its way not to invalidate optimizations. Java had the aim of producing the same results in all platforms.





I recommend that you do not use this ambiguous construction in your code. But this was a good question.





Nelson Bittencourt


See more in my site:


http://www1.webng.com/nbittencourt/index...


No comments:

Post a Comment