wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes thie output is different in C and JAVA Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "thie output is different in C and JAVA" Watch "thie output is different in C and JAVA" New topic
Author

thie output is different in C and JAVA

sharma sachin
Greenhorn

Joined: Nov 13, 2009
Posts: 24

The output of the program is 1 but in C the output of the same program is 2
can any one explain why it is happening


and the other query is in java the size of int and float is 32 bits
then according to the size float value can assigned in to the int variable just like C language
but in case of JAVA it is achieve with the help of explicit-typecasting why it is so???
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2771
    
  10

For your first question, I think what happens is Java picks out the value of i before it's incremented (1), then increments it (making it 2) then assigns the picked out value back to i (making it 1 again). With C, edge cases like that can actually depend on which compiler you use. Ultimately though, the solution is the same in both C in Java: don't write code like that.

Java is stricter about casting than C is, and when you cast a float to int, for example, you are telling it to truncate off the fractional part. C is a lot more flexible. I'm a bit fuzzy on what would happen if you just assigned a float to an int variable, but when you access things through pointers, it would be possible to just interpret the bits in the float as an int, and the numerical values would only be vaguely related to each other.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36478
    
  16
You only think it returns 2 in C. You need to try it on several different compilers, and see how many of them return 2.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10909
    
  12

This may help.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Anand Hariharan
Rancher

Joined: Aug 22, 2006
Posts: 257

http://c-faq.com/expr/ieqiplusplus.html


"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- Antoine de Saint-Exupery
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36478
    
  16
Anand Hariharan wrote:http://c-faq.com/expr/ieqiplusplus.html
That link has it exactly right.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thie output is different in C and JAVA
 
Similar Threads
Automatic Conversion / Cast
wrappers
overloaded methods
Unable to understand toArray()
Method Overloading