Game Development Reference
In-Depth Information
4.2.3 Instructions and Expressions
If you look at the elements in the syntax diagrams, you have probably noticed that
we called the value or program fragment on the right-hand side of an assignment
an expression . So what is the difference between an expression and an instruction ?
The difference between the two is that an instruction changes the memory in some
way, whereas an expression has a value. Examples of instructions are method calls,
or assignments, as we have seen in the previous section. Instructions often use ex-
pressions. Here are some examples of expressions:
16
numberOfBananas
2
a+4
numberOfBananas + 12
a
3
Color.Olive
All these expressions represent a value of a certain type . Except for the last line, all
expressions are of type int . The last line retrieves a property of the Color class and it
returns a color value. The type of this color value is Color . So, although it may seem
confusing, a class is actually also a type. How this works exactly is something that
we will discuss later on.
4.2.4 Arithmetic Operators
In int expressions, the following arithmetic operators can be used:
+ add
subtract
multiply
/ divide
% remainder after division (pronounce as 'modulus')
For multiplication an asterisk is used, because the signs regularly used in mathe-
matics (
) are not on a computer keyboard. Completely omitting this operator,
as is done also in mathematics (for example in the formula f(x)
·
or
×
3 x ), is not al-
lowed in C# because it introduces confusion with variables consisting of more than
one character.
When the division operator / is used, the result is truncated, because a calculation
with two int variables results in another int variable. For example, the result of the
expression 14/3 is 4.
The special operator % gives the remainder after division. For instance, the result
of 14%3 is 2, and the result of 456%10 is 6. The result will always lie between 0 and
the value at the right side of the operator. The result is 0 if the result of the division
is integral.
=
Search WWH ::




Custom Search