Trying to understand `w = w + 1` from a math perspective?

Just looking at the first line in the example, and I don’t agree with the syntax of “w=w+1” as this implies that w=w+1 which it isn’t. Doesn’t anyone think it should be written as w sub 1 “so a little 1 at the bottom right of the w”?

1 Like

To anyone first exposed to programming this is a head turner, to be sure. It looks nothing like any math we learned in school.

Break it down though…

w + 1

will be one more than what w is currently.

w = w + 1

is the reassignment of the new outcome to the original variable. Now w is one more than it was, previously.

This is not a formula but an assignment statement that assigns the value of the expression on the right of the equal sign to the variable on the left side. Evaluation of the expression occurs first, then the assignment.

Once we can grasp what is happening, and see that it is perfectly logical, and practical (as it increments w) we can appreciate the shorthand operator that many languages have to simplify the above statement… Augmentation assignment.

w += 1

Like above, the current value a w is increased by 1, then reassigned. The operation occurs before the assignment.

When you get into loops, you will see another operator introduced that shortens the expression even more… ++

w++

increments w in place. That will come up, so don’t tarry on this problem but push ahead.

88 Likes

Great explanation, thank you!

8 Likes

“This is not a formula, but an assignment statement.” The key line in the explanation!

1 Like

so if this is the reassignment, does w now equal 5?

If we assume that w is 4, then yes. It becomes the outcome of the expression on the right. The variable on the left could be any variable, but in this case we want to update the value of the existing variable. The old value is overwritten with that assignment.

Technically, it is not overwritten, but pointed to the new value. w + 1 is computed and stored in memory, likely at a new location. The old location will be garbage collected by the system. Of course this doesn’t matter to us.

1 Like

Thanks for the quick response, it certainly makes it more clear to me now. Having revisited the example given in the lesson, it logs w as 5 after the reassignment but now I understand why.

1 Like