More Assignment Operators

The assignments like x = x + 5 are so common that C has special operators for them, called compound assignment operators. For most arithmetic operators, like +, -, etc., there is a compound assignment operator +=, -=, etc., which works this way:

The value of an assignment operator is the assigned value

All assignment operators in C can be used as a part of any arithmetic expression, and their value is the value that is assigned.

Maybe an example will show what I mean. Let's say you have two variables, int x and int y, and then you assign

y = 5;
x = y;

Obviously, both x and y will be 5 after this. It can be written this way instead:

x = (y = 5);

because y = 5 is an expression that evaluates to 5, and then this 5 is assigned to x. Brackets are optional:

x = y = 5; /* works as well */

The same thing works for compound assignments, even though it's much less readable. But you can write x = (y += 5), which will increase y by 5, and assign the result to x. It's borderline unreadable though, so don't normally write my code this way.

Increment and decrement

Two very special cases: x += 1 and x -= 1 – have their own special operators ++ and --. To increment x by 1, you can write x++ or ++x. The important difference between these two is in the result of this: the prefix ++x returns the new value, while the postfix x++ returns the old value. Now if this is too hard to understand, it's OK; we'll come back to this topic later. For now, you can just use ++x whenever you want to increment x by 1.

For decrementing by one, --x works the same way.

All this information might seem pretty random, but it will prove to be very useful soon, when we learn about some cases where it is very natural to use an assignment operator in a condition expression of a while loop:

while (x = something) { /* note: assignment, not comparison! */
	...
}

Why would any reasonable person need that? I'll show you soon.