|
Statement
size = 2;stores 2 into variable size . A statement that stores a value into a variable is called an assignment statement.
Notice that an assignment statement does not begin with a type. Writing a type turns an assignment statement into a declaration of a new variable.
The right-hand side of = can be any expression. Assignment statement
v = E;is performed by first evaluating E, then storing the value of E into variable v.
You can store a value into more than one variable in one statement. For example,
x = y = 0;stores 0 into both x and y.
You can use a variable in (almost) any place where you can use a constant. For example,
int x, y;
x = 2;
y = x + 3;
ends with y = 5.
It is easy to change the value of a variable in an assignment statement. For example,
int x;
x = 1;
x = x + 2;
ends with x = 3. The third line first gets the value
of x (1) and evaluates 1 + 2, yielding 3. Then it stores
3 into x.
When you use a variable, you always get the current value of that variable. For example
int x, y;
x = 1;
x = x + 2;
y = x;
x = x + 1;
ends with y = 3.
What is the value of y after the following?
int y;
y = 2;
y = y + 1;
y = y + 1;
Answer
What is the value of y after the following?
int y;
y = 2;
y + 1;
y + 1;
Answer
What is the value of variable r after the following?
double r = 2/3;Answer
|