11.5 Assignment Operators

11.5.1 Assignment (=)

We already met the assignment operator when talking about variables (Section 9.3). The = operators can be applied to a variable and an expression; expression is evaluated and result is assigned to variable and returned.

variable_name = expression;

The important point is that result is returned by the = operator so you can use an assignment operation as an expression:

print (foo = bar = 5);

will define two variables called foo and var, store the number 5 within both variables, and print 5.

That's what happens: Cows will execute the assignment operation bar=5, so bar is defined and its value is 5. Since the = operator also returns the assigned value, foo = bar = 5 is reduced, after the assignment, to foo = 5. So foo is now defined, 5 is returned again and correctly displayed by the print () statement.

11.5.2 Assignment with Operations

Consider the following assignment expression:

x = x + 10;

We are incrementing x by 10, so we are assigning x a new value, depending on x itself.

Every time you have an expression in the form:

variable = variable <operator> expression

you can use the following, equivalent shortcut:

variable <operator>= expression

The following operators for assignment with operations are supported:

x += 10

is a shortcut for x = x + 10

x *= y

is a shortcut for x = x * y

x /= (y -= 2)

is a shortcut for y = y - 2; x = x / y

11.5.3 Increment (++)

The ++ operator increments its operand by one; the value returned depends on the position of the operator respect to the operand:

x = 5; y = x++;

x is incremented by one so its value is 6; y's value is 5.

x = 5; y = ++x;

Both variables store the number 6

11.5.4 Decrement (-)

The - operator decrements its operand by one; the value returned depends on the position of the operator respect to the operand:

x = 5; y = x-;

x is decremented by one so its value is 4; y's value is 5.

x = 5; y = -x;

Both variables store the number 4.

This manual can be downloaded from http://www.g-cows.org/.