int i=2;
i = ++i + ++i + ++i;
Which is more correct? Java's result of 12 or C = 13. Or if not a matter of correctness, please elaborate.
C is more procedure-oriented. Java is more data-oriented. C is a middle-level language because binding of the gaps takes place between machine level language and high-level languages. Java is a high-level language because translation of code takes place into machine language using compiler or interpreter.
C is a procedural, low level, and compiled language. Java is an object-oriented, high level, and interpreted language. Java uses objects, while C uses functions. Java is easier to learn and use because it's high level, while C can do more and perform faster because it's closer to machine code.
C is a middle-level language as it binds the bridges between machine-level and high-level languages. Java is a high-level language as the translation of Java code takes place into machine language, using a compiler or interpreter. C is only compiled and not interpreted. Java is both compiled and interpreted.
1) Java is simpler, the syntax is much more readable than C, C++ or any other language. 2) Java is good to learn Object-Oriented programming, but not so good for procedural one, prefer C there.
Java guarantees (§15.7.1) that it will be evaluated left-to-right, giving 12. Specifically, ++
has higher precedence that +
. So it first binds those, then it associates the addition operations left to right
i = (((++i) + (++i)) + (++i));
§15.7.1 says the left operand is evaluated first, and §15.7.2 says both operands are evaluated before the operation. So it evaluates like:
i = (((++i) + (++i)) + (++i));
i = ((3 + (++i)) + (++i)); // i = 3;
i = ((3 + 4) + (++i)); // i = 4;
i = (7 + (++i)); // i = 4;
i = (7 + 5); // i = 5;
i = 12;
In C, it is undefined behavior to modify a variable twice without a sequence point in between.
There is nothing like more correct. It is actually undefined and its called Sequence Point Error. http://en.wikipedia.org/wiki/Sequence_point
The Java result makes sense to me because the operators give the result you would expect, but no serious program should contain a statement like this.
EDIT: I'm amused that this one sentence response has been my highest scored answer of the evening (compared to the dozen other answers I posted, some with pages of code samples). Such is life.
In C this is undefined behavior. There is no correct behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With