In review question 8 for chapter 2 of the OCP 17 the following lines of code are presented:
In the answer it is said that it results in pigs value being unchanged, because pig++ returns the value before it's incremented. But my thinking is: Yes the value returned is 4, and then the variable is incremented. Why is that wrong? We are told in the chapter that it's perfectly legal to assign variables in the middle of an expression. Here is an example given in the chapter:
In my mind these two examples are almost identical since var++; is equivalent to var = var + 1; Again, what am I missing/misunderstanding?
But pig++ is NOT equivalent to pig = pig + 1, because the first expression returns the old value of pig, while the second expression returns the new value of pig.
See if the following example explains a little bit better what happens in the original code.
Just calling postIncrement() would result in pig having the value 5, but if you instead call pig = postIncrement(), after incrementing pig to 5, you are immediately overwriting that value by assigning the old value of pig back to pig.
That actually helps!
I guess what I got hung up on was the fact that whereas the pre-increment increments the value and then returns it I imagined the post-increment operator functioning like "returning the value, then incrementing it". In my defence the name makes it sound like that , but when I reread that part of the chapter it never actually said that. It just said "returns the original value".
Thank you for explaining!
Olle Djerf wrote:. . . post-increment operator functioning like "returning the value, then incrementing it". . . . the name makes it sound like that . . .
It is called post‑increment because it is written with a postfix operator (at least I think it is). It isn't so much, “returning the value, then incrementing it,” as, “incrementing the value, then hiding it.” The increment occurs, but it isn't visible until the next time the variable is used. The Java® Language Specification (=JLS) says,
the value 1 is added to the value of the variable and the sum is stored back into the variable. . . . The value of the postfix increment expression is the value of the variable before the new value is stored.
Same as returning the original value. It says more or less the same fori--. It also says,
The result of the postfix increment expression is not a variable, but a value.
That restricts the use of some other operators oni++, etc.
There is a good chance of having questions about postfix operators because they cause so much confusion to beginners.
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop