Java Forum / General / December 2006
Q about increment and assignment
Big D - 23 Dec 2006 22:19 GMT I'm confused by the output of the following code:
public class PP { public static void main(String[] args) { int i = 1; i = i++; System.out.println(i); } }
It outputs 1.
I understand the assignment operator happening before the ++, but I don't understand why the ++ doesn't increment. I thought the statement should basically expand to:
i = i; i = i+1;
but the ++ gets lots somewhere...
John W. Kennedy - 23 Dec 2006 22:24 GMT > I'm confused by the output of the following code: > [quoted text clipped - 16 lines] > > but the ++ gets lots somewhere... No, it gets expanded into:
t = i; i = i + 1; i = t;
Don' do dat!
 Signature John W. Kennedy "The blind rulers of Logres Nourished the land on a fallacy of rational virtue." -- Charles Williams. "Taliessin through Logres: Prelude"
Karl Uppiano - 24 Dec 2006 02:50 GMT >> I'm confused by the output of the following code: >> [quoted text clipped - 24 lines] > > Don' do dat! Holy crap! I hope no one ever asks me to evaluate code like that on a job interview. I would never write code like that, but I doubt if I'd squirt that nuance from the top of my head.
John W. Kennedy - 24 Dec 2006 03:05 GMT >>> I'm confused by the output of the following code: >>> [quoted text clipped - 27 lines] > interview. I would never write code like that, but I doubt if I'd squirt > that nuance from the top of my head. Java is an improvement over its ancestor, C. In C, the official interpretation of the code in question is "whatever the compiler feels like doing". Because Java places such an emphasis on portability, it sets down rules.
 Signature John W. Kennedy "The blind rulers of Logres Nourished the land on a fallacy of rational virtue." -- Charles Williams. "Taliessin through Logres: Prelude"
Karl Uppiano - 24 Dec 2006 03:29 GMT >>>> I'm confused by the output of the following code: >>>> [quoted text clipped - 32 lines] > like doing". Because Java places such an emphasis on portability, it sets > down rules. That is a Good Thing(TM). I'm not disputing that. But I doubt I could quote chapter and verse from the JLS off the top of my head. I'm an open-book-test kind of guy (it's how the real world works anyway. No employer I know of would require you to work without access to any kind of reference materials). I'm just sayin'...
John Ersatznom - 24 Dec 2006 13:44 GMT > That is a Good Thing(TM). I'm not disputing that. But I doubt I could quote > chapter and verse from the JLS off the top of my head. I'm an open-book-test > kind of guy (it's how the real world works anyway. No employer I know of > would require you to work without access to any kind of reference > materials). I'm just sayin'... Agreed. In fact, if you're even thinking of reaching for an official specification or asking a language lawyer to be sure of what some code will do, it's a sign that the code in question is excessively obscure and should be rewritten to be more self-documenting.
If I were giving a job interview, and I did include code like that on it, the best answer I would be looking for from a potential hire would be "I don't know for sure, but I wouldn't write code like that anyway, and I'd hope to hell anyone who did would document it for me." :)
Patricia Shanahan - 24 Dec 2006 17:03 GMT >> That is a Good Thing(TM). I'm not disputing that. But I doubt I could >> quote chapter and verse from the JLS off the top of my head. I'm an [quoted text clipped - 11 lines] > be "I don't know for sure, but I wouldn't write code like that anyway, > and I'd hope to hell anyone who did would document it for me." :) Oh well, that's one job I would never get. Personally, I think knowing exactly what statements with multiple side effects do is useful, because it makes it easier to replace them with functionally equivalent but more readable code. It's not as though the Java model of ++ and -- is in any way messy, unmemorable, or difficult to understand.
Patricia
John Ersatznom - 24 Dec 2006 17:43 GMT >> If I were giving a job interview, and I did include code like that on >> it, the best answer I would be looking for from a potential hire would [quoted text clipped - 6 lines] > readable code. It's not as though the Java model of ++ and -- is in any > way messy, unmemorable, or difficult to understand. It's the "I wouldn't write code like that anyway" part I'd consider most important. If you could clean up code like that written by someone else, so much the better, especially if you could do it even when the "someone else" hadn't documented it. :)
Mike Schilling - 24 Dec 2006 03:27 GMT > Holy crap! I hope no one ever asks me to evaluate code like that on a > job interview. I would never write code like that, but I doubt if I'd > squirt that nuance from the top of my head. I'll have to make that an interview question. If you answer anything other than "I would *never* write code like that", you wouldn't get the job.
Stefan Ram - 24 Dec 2006 03:50 GMT >I'll have to make that an interview question. If you answer anything other >than "I would *never* write code like that", you wouldn't get the job. Such code might make perfect sense, for example, as part of a Java compiler test suite.
Mike Schilling - 24 Dec 2006 08:28 GMT >>I'll have to make that an interview question. If you answer anything >>other >>than "I would *never* write code like that", you wouldn't get the job. > > Such code might make perfect sense, for example, as part of a > Java compiler test suite. As it happens, I don't hire Java compiler writers. For the usual purposes of code writing (to implement algorithms), there's no excuse for writing code whose meaning is that obscure, any more than there's an excuse for
int sum(int []arr) { int sum = 0; int i = 0; try { while(true) { sum += arr[i++]; } catch (ArrayIndexOutOfBoundsException ex) { return sum; } }
Stefan Ram - 25 Dec 2006 18:05 GMT >>Such code might make perfect sense, for example, as part of a >>Java compiler test suite. >As it happens, I don't hire Java compiler writers. »Compiler suite test writer« is quite a different job than »compiler writer«.
I also deem the answer prefered by you (»I would *never* write code like that«) somewhat inappropriate. It is as if I'd ask a student:
»What might happen to a human when he is touching hydrochloric acid?«
and the student would answer:
»I would never perform an action like that.«
Mike Schilling - 26 Dec 2006 00:08 GMT >>>Such code might make perfect sense, for example, as part of a >>>Java compiler test suite. >>As it happens, I don't hire Java compiler writers. > > »Compiler suite test writer« is quite a different job than > »compiler writer«. I hire even fewer of them.
Patricia Shanahan - 24 Dec 2006 04:20 GMT >>> I'm confused by the output of the following code: >>> [quoted text clipped - 27 lines] > interview. I would never write code like that, but I doubt if I'd squirt > that nuance from the top of my head. Variations on the exact effect of various combinations of prefix/postfix ++/-- are frequently asked questions in this newsgroup. I've seen the questions often enough to remember how to work out the answers. The fact that the JLS has a very simple, consistent, well-defined model makes them quite easy to answer.
The only time I've ever coded something like that in Java was when checking my answers for more complicated cases.
Patricia
Alex Hunsley - 25 Dec 2006 19:39 GMT >>>I'm confused by the output of the following code: >>> [quoted text clipped - 28 lines] > interview. I would never write code like that, but I doubt if I'd squirt > that nuance from the top of my head. It's actually quite easy to derivce the code that John posted, if you remember the core rule about "evaluation": post-increment operators like i++ affect the value of the variable you apply them to *after* the whole "i++ " expression is evaluated (and when you write "x = [something]", you are evaluating the "[something]"). Pre-increment operators like ++i affect the value of i *before* i is evaluated in the "i++" expression.
lex
jupiter - 24 Dec 2006 18:07 GMT >> I'm confused by the output of the following code: >> [quoted text clipped - 20 lines] > > t = i; John, is t a copy of the bits in i made by the postfix ++ method?
> i = i + 1; > i = t; Is it fair then to say that t gets restored because of the way the postfix operator applies only after the expression is evaluated?
What is the difference between the original problem and this one?
int i=1; System.out.println("i=" + i++); //output=1 System.out.println("i=" + i);//output=2
I find this one easier to understand because eventually the new bits do output. They don't get overwritten. In the original problem there is overwriting going on that cause the 2 value to be lost entirely. Is this due to the self-referencing aspect of the original problem i=i++;?
One last question: Where is that temp copy of the bits visible? I can't see it in a debugger, so maybe I'm not using it (Eclipse) to great advantage. I see the original i bits on the stack and that's about it. This should not involve heap storage, so that leaves me wondering where/how I'd ever see that temp set of bits.
thanks ...
John W. Kennedy - 24 Dec 2006 22:08 GMT >>> I'm confused by the output of the following code: >>> [quoted text clipped - 21 lines] > > John, is t a copy of the bits in i made by the postfix ++ method? For explanatory purposes, I've eliminated the ++ altogether.
>> i = i + 1; >> i = t;
> Is it fair then to say that t gets restored because of the way the > postfix operator applies only after the expression is evaluated? My t does not exist in the postfix version at all, so in one sense the question is meaningless, but yes, I guess you could say so.
> What is the difference between the original problem and this one?
> int i=1; > System.out.println("i=" + i++); //output=1 > System.out.println("i=" + i);//output=2 It doesn't have the expression "i = i++", which is bad coding, though technically legal.
> I find this one easier to understand because eventually the new > bits do output. They don't get overwritten. In the original problem > there is overwriting going on that cause the 2 value to be lost > entirely. Is this due to the self-referencing aspect of the > original problem i=i++;? Yes, that's the key.
> One last question: Where is that temp copy of the bits visible? I > can't see it in a debugger, so maybe I'm not using it (Eclipse) to > great advantage. I see the original i bits on the stack and that's > about it. This should not involve heap storage, so that leaves me > wondering where/how I'd ever see that temp set of bits. It isn't visible at the Java level, though it will be seen in the bytecode (does Eclipse have an option to trace at the bytecode level? I've never had occasion to try). But "i=i++" is bad, evil, wicked, perverse, satanic, blood-sucking, kitten-murdering, baby-raping, Bush-voting malpractice, so Just Don't Do It.
 Signature John W. Kennedy "The blind rulers of Logres Nourished the land on a fallacy of rational virtue." -- Charles Williams. "Taliessin through Logres: Prelude"
Patricia Shanahan - 24 Dec 2006 23:08 GMT >>> I'm confused by the output of the following code: >>> [quoted text clipped - 21 lines] > > John, is t a copy of the bits in i made by the postfix ++ method? The sample code is a Java equivalent to the original statement.
>> i = i + 1; >> i = t; [quoted text clipped - 7 lines] > System.out.println("i=" + i++); //output=1 > System.out.println("i=" + i);//output=2 The new version does not assign the result of i++ to i, so the increment side effect does not get overwritten by the value of i++.
> I find this one easier to understand because eventually the new > bits do output. They don't get overwritten. In the original problem > there is overwriting going on that cause the 2 value to be lost > entirely. Is this due to the self-referencing aspect of the > original problem i=i++;? It is not a self reference problem so much as an issue of multiple side effects that act on the same data item. Generally, multiple side effects in one statement make it harder to read and understand, and so should be avoided. Code with multiple side effects on the same bits is a particularly bad idea.
> One last question: Where is that temp copy of the bits visible? I > can't see it in a debugger, so maybe I'm not using it (Eclipse) to > great advantage. I see the original i bits on the stack and that's > about it. This should not involve heap storage, so that leaves me > wondering where/how I'd ever see that temp set of bits. The JVM can do it any way it likes, as long as it gets the proper results and side effects. It is not required to make a temporary variable anywhere that would be visible, as long as it ensures the following:
1. Side effects happen in the proper order. Specifically, all side effects of evaluating the right hand side of an assignment must happen before the assignment.
2. The value of i++ is the old value of i.
Patricia
Mike Schilling - 24 Dec 2006 23:50 GMT > It is not a self reference problem so much as an issue of multiple side > effects that act on the same data item. Generally, multiple side effects > in one statement make it harder to read and understand, and so should be > avoided. Code with multiple side effects on the same bits is a > particularly bad idea. Thought expermients:
1. Can "multiple side effects on the same bits" be defined clearly and intuitively? 2. If so, would it be feasible to make statements that contain them illegal? E.g.
i = i++;
wiuld cause a compilation error.
3. If so, would this be an improvement?
John W. Kennedy - 25 Dec 2006 00:08 GMT >> It is not a self reference problem so much as an issue of multiple side >> effects that act on the same data item. Generally, multiple side effects >> in one statement make it harder to read and understand, and so should be >> avoided. Code with multiple side effects on the same bits is a >> particularly bad idea.
> Thought expermients:
> 1. Can "multiple side effects on the same bits" be defined clearly and > intuitively? Both at once? Probably not. Otherwise, yes.
(By the way, this is Java we're talking about, so "same variable" will suffice.)
> 2. If so, would it be feasible to make statements that contain them illegal? > E.g.
> i = i++;
> wiuld cause a compilation error. I suspect so.
> 3. If so, would this be an improvement? Well, some people would scream "Hand-holding!" and run off to comp.lang.ruby to complain about the newest way Sun is Suppressing their Creativity. (Note: I like Ruby. I use it a lot. But not beyond the limits of Exodus 20:4-7.)
 Signature John W. Kennedy "The blind rulers of Logres Nourished the land on a fallacy of rational virtue." -- Charles Williams. "Taliessin through Logres: Prelude"
John Ersatznom - 27 Dec 2006 01:05 GMT > Well, some people would scream "Hand-holding!" and run off to > comp.lang.ruby to complain about the newest way Sun is Suppressing their > Creativity. (Note: I like Ruby. I use it a lot. But not beyond the > limits of Exodus 20:4-7.) 70% of the planet's population won't have a bible handy when they reach that statement.
I know I don't.
Actually quote it or at least link to it please. :P
John W. Kennedy - 27 Dec 2006 01:33 GMT >> Well, some people would scream "Hand-holding!" and run off to >> comp.lang.ruby to complain about the newest way Sun is Suppressing [quoted text clipped - 5 lines] > > I know I don't. <URL:http://www.bible.com> (among many, many others)
Thou shalt not make unto thee any graven image, or any likeness of any thing that is in heaven above, or that is in the earth beneath, or that is in the water under the earth.
Thou shalt not bow down thyself to them, nor serve them: for I the LORD thy God am a jealous God, visiting the iniquity of the fathers upon the children unto the third and fourth generation of them that hate me;
And shewing mercy unto thousands of them that love me, and keep my commandments.
Thou shalt not take the name of the LORD thy God in vain; for the LORD will not hold him guiltless that taketh his name in vain.
...which is infinitely too verbose for my original rhetorical purpose.\
 Signature John W. Kennedy "The blind rulers of Logres Nourished the land on a fallacy of rational virtue." -- Charles Williams. "Taliessin through Logres: Prelude"
John Ersatznom - 27 Dec 2006 04:53 GMT >>> Well, some people would scream "Hand-holding!" and run off to >>> comp.lang.ruby to complain about the newest way Sun is Suppressing [quoted text clipped - 23 lines] > > ...which is infinitely too verbose for my original rhetorical purpose.\ Thanks -- though the URL you provided does not link to that specific passage, and one that did would have sufficed without being "too verbose" :)
Patricia Shanahan - 25 Dec 2006 00:32 GMT >> It is not a self reference problem so much as an issue of multiple side >> effects that act on the same data item. Generally, multiple side effects [quoted text clipped - 12 lines] > > wiuld cause a compilation error. I'm afraid not feasible to do exactly in general.
class MyClass{ int n; }
MyClass p,q; ...
p.n = q.n++;
The two side effects in this statement affect the same bits if, and only if, p and q reference the same MyClass instance. Whether that ever happens is not, in general, a computable function of the source code.
Of course, one might do the equivalent of definite assignment, a set of computable rules that prohibit all the bad cases, as well as some non-problems.
> 3. If so, would this be an improvement? It's too late now, but I think Java might have been a better language if assignment, += etc., ++ and -- had all been made statements, rather than expressions. That is, they would ONLY have side effects, not values.
There would still be more indirect multiple side effects, but generally they are used in more restrained ways.
Patricia
Patricia Shanahan - 23 Dec 2006 22:37 GMT > I'm confused by the output of the following code: > [quoted text clipped - 16 lines] > > but the ++ gets lots somewhere... In Java, any side effects of operand evaluation happen before side effects of the operation that uses the operands. i++ will be completely evaluated before the assignment of its value to i.
The value of "i++" is, by definition, the value of i prior to the increment, so the assignment restores the old value of i. The code is equivalent to:
int temp = i; // record the value of i++, the old value of i i = i+1; // increment i i = temp; // assign the value of i++ to i.
Patricia
zeromonge@gmail.com - 24 Dec 2006 04:42 GMT Hi, this is not gonna work like you write it. Look if you do i = i++; it will asign i = i because it evaluates i and after that it increments.
You should do:
i = ++i;
If you only want to increment "i" then just do:
public static int main(String[] args) { int i = 1; i++; System.out.println("The value of variable i is: " + i ); return 0; } }
Output = 'The value of variable i is: 2'
> I'm confused by the output of the following code: > [quoted text clipped - 16 lines] > > but the ++ gets lots somewhere... John W. Kennedy - 24 Dec 2006 05:12 GMT > Hi, this is not gonna work like you write it. Look if you do i = i++; > it will asign i = i because it evaluates i and after that it > increments. You are right about the result, as far as it goes, but why are you giving a confusing and imprecise explanation after two of us have given exact descriptions?
> You should do: > > i = ++i; No, he shouldn't. It's true that this statement works, but it's stupid. The correct statement is:
++i;
or
i++;
(I personally prefer the first, but the second is more common in the wild.)
And don't top-post.
 Signature John W. Kennedy "The blind rulers of Logres Nourished the land on a fallacy of rational virtue." -- Charles Williams. "Taliessin through Logres: Prelude"
Luc The Perverse - 24 Dec 2006 06:36 GMT > No, he shouldn't. It's true that this statement works, but it's stupid. > The correct statement is: [quoted text clipped - 4 lines] > > i++; He didn't write either of them
He was trying to understand part of a test which deliberately used operators in an unusual way to test one's understanding. The practicality of such a test, or the implications on actual programming ability are questionable. But it should suffice to eliminate those completely inept.
-- LTP
:) Luc The Perverse - 24 Dec 2006 05:33 GMT > I'm confused by the output of the following code: > [quoted text clipped - 16 lines] > > but the ++ gets lots somewhere... Yes
++ is a function, which does two things - returns a value, and changes the variable.
i=i++; the function i++ must be calculated first before the final assignment is completed.
i= (i++);
i++ returns i, so you can reduce it to
i=i;
In other words, the ++ is not being lost, it is just being overwritten.
int i = 1; i = i++;
is the same as writing
int i = 1; int oldval = i; i = i + 1; i = oldval;
-- LTP
:) Big D - 24 Dec 2006 14:15 GMT Thanks for the explanation, all. Obviously the temporary variable was the key to this caper.
Alex Hunsley - 25 Dec 2006 19:37 GMT > I'm confused by the output of the following code: > [quoted text clipped - 16 lines] > > but the ++ gets lots somewhere... Other have answered the exact why. But anyway, this is a great illustration of why you should only ever use, IMO, the increment decrement operators in the simplest way, i.e.:
i++;
or
i--;
Otherwise, confusion results, as you've discovered. And of course, you may write "i += 1" or "i -= 1" rather than the above form.
Python is a example of a language where they ditched the increment/decrement operators, and at no loss, only benefit!
lex
sandy - 26 Dec 2006 05:48 GMT All Group Friends
The Ans. of this coding always remain 1. because statement i=i++; in this statement i's value assign to i and after assignment it increases the value of i. So, i's value is eqaul to 1.
Sumit Tanwar
> I'm confused by the output of the following code: > [quoted text clipped - 16 lines] > > but the ++ gets lots somewhere... Patricia Shanahan - 26 Dec 2006 18:35 GMT > All Group Friends > [quoted text clipped - 3 lines] > increases the value of i. > So, i's value is eqaul to 1. I agree with the conclusion, but don't see how it follows from your model. It does, of course, follow from the model used in the JLS, as discussed in several messages in this thread.
"i's value assign to i" would make i equal to 1. "after assignment it increases the value of i" would change i from 1 to 2.
Patricia
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|