aspose file tools
The moose likes Beginning Java and the fly likes why different outputs in c++ and java!? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "why different outputs in c++ and java!?" Watch "why different outputs in c++ and java!?" New topic
Author

why different outputs in c++ and java!?

sandeep vijan
Greenhorn

Joined: Dec 28, 2000
Posts: 7
the following snippet gives different outputs in c++ and
java:
int i = 0;
i = i++;
i = i++;
i = i++;
i = i++;
System.out.println("i = " + i);//output is: i = 0
//printf("i = %d" + i);//output is: i = 4
why is this difference in outputs?
i will appreciate if anyone can point this difference in
behaviour (specially if java syntax is based on c/c++).

------------------
))
((
C|~~|
`--'
JAVA

. ))<BR>. ((<BR>. C|~~|<BR>. `--'<BR>. JAVA
Kalidas Pavi
Ranch Hand

Joined: Nov 20, 2000
Posts: 42
Sandeep,
Use prefix increment instead of postfix increment operator and we can get the output in java.
int i=0;
i = ++i;
i = ++i;
System.out.println("i = "+i);
the above code snippet will give the result of i = 2
Here the difference is obvious from the difference between post fix and prefix operators..

Let me try to explain why the post fix operation is not working
Refer to the JLS 15.13.2 Postfix increment operator ++
"PostfixExpression ++"
The result of the postfix increment expression is not a variable, but a value.
At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs.
Refer to JLS 15.25 Assignment operators
"LeftHandSide AssignmentOperator AssignmentExpression"
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.
Based on the above, In the first instance the assignment expression was i++, and the left hand side (i) is assigned with a value of 0 before the postfix increment.
Once the assignment has occured Since i is already assigned with a value and the postfix operator is trying to operate on the same (which is a value and not a variable) the postfix operation fails.
whereas in the case of prefix increment the increment occurs before the assignment.
There are some differences between the parsers used for c++ and java which i am afraid is too much for me to digest!!
I hope i have not confused you.
Kalidas.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: why different outputs in c++ and java!?
 
Similar Threads
equals() method
regex question from K & B
Got an unexpected out-of-bounds exception
Difference in output
Understanding Byte Data and Character Encoding