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.
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:
+=
-=
*=
/=
%=
**=
is a shortcut for x = x + 10
is a shortcut for x = x * y
is a shortcut for y = y - 2; x = x / y
The ++ operator increments its operand by one; the value returned depends on the position of the operator respect to the operand:
x++ increments x by one but returns the original value (before increment)
++x increments x by one and then returns x
x
is incremented by one so its value is 6; y
's value is 5.
Both variables store the number 6
The - operator decrements its operand by one; the value returned depends on the position of the operator respect to the operand:
x- decrements x by one but returns the original value (before decrement)
-x decrements x by one and then returns x
x
is decremented by one so its value is 4; y
's value is 5.
Both variables store the number 4.
This manual can be downloaded from http://www.g-cows.org/.