Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 346 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
++i + ++i + ++i in Java vs C

#1
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.
Reply

#2
There is nothing like more correct. It is actually undefined and its called Sequence Point Error.

[To see links please register here]

Reply

#3
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.
Reply

#4
Java guarantees ([§15.7.1][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][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.

[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#5
In C this is undefined behavior. There is no correct behavior.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through