Game Development Reference
In-Depth Information
So now we have shown one instruction for declaring a variable, and another
instruction to store a value in it. But if you already know which value you want to
store in a variable when you declare it, you can combine the declaration of a variable
and the first assignment to it:
int red = 3;
Here are a few examples of more declarations and assignments of integer variables:
int age = 16;
int numberOfBananas;
numberOfBananas = 2;
int a, b;
a=4;
int c = 4, d = 15, e =
3;
c=d;
numberOfBananas = age + 12;
In the fourth line of this example, you see that it is possible to declare multiple
variables in one declaration. You can even perform multiple declarations with as-
signments in a single declaration, as can be seen in the sixth line of the example
code. On the right hand side of the assignment, we can put other variables, or math-
ematical expressions, as you can see in the last two lines. The instruction c=d;
results in the value stored in variable d being stored as well in variable c . Since the
variable d contains the value 15, after this instruction is executed the variable c also
contains the value 15. The last instruction takes the value stored in the variable age
(16), adds 12 to it and stores the result in the variable numberOfBananas (which now
has the value 28). In summary, the memory will look something like this after these
instructions have been executed:
The syntax of declaring variables (with an optional initialization) is expressed in
the following diagram:
 
Search WWH ::




Custom Search