tcTitleRunning
tcTitleSlide
Code
Board
Trace
Description
We start with empty
Note that in trace
u
means undefined variable-
means defined but uninitialized variable?
means your turn to answerAt this point all variables are undefined.
int a;
is a declaration statement. It declares that variable a
is of type int
.
It causes a number of actions:
a
int
a
?
.a = 4;
is an assignment statement. It changes the value of a variable, which is already defined.
a
to 4
.int b = 5;
has the same effect of
int b;
b = 5;
It causes both declaration and initialization:
b
int
b
b
to 5
.int c = 7;
is not any different than int b = 5;
.
We will focus on variable c
little bit more.
c = 8;
sets the content of c
to 8
.
Isn't it similar to a = 4
?
Note that
Note that
c = a;
is little tricky. It means take the content of a
put into c
.
Then what happens to the content of a
? Does it become undefined? Try to run the code and
see.
So does this:
c = 9;
It changes the content of c
once more. Now it becomes 9
.
Do you expect that this statement causes a side effect and the content of a
also changes?
double d;
is a declaration statement. It declares that variable d
is of type double
.
It causes a number of actions:
d
double
d
?
.d = 1.2;
is an assignment statement. It changes the value of a variable, which is already defined.
d
to 1.2
.d = a;
is another assignment statement similar to c = a
. But there is a very important difference.
c = a
, both a
and c
were of type int
.d = a;
, there is a type mismatch.d
becomes 4
.This is similar to the previous statement.
a = d;
d
is 4
. So we do not expect any problem.Run the code
...
int a;
a = 4;
int b = 5;
int c = 7;
c = 8;
c = a;
c = 9;
double d;
d = 1.2;
d = a;
a = d;
...
. 2 3 4 5 6 7 8 9 10 11 12
Statement | a b c d ---------- + - - - -- int a; | - u u u a = 4; | 4 u u u int b = 5; | 4 5 u u int c = 7; | 4 5 7 u c = 8; | 4 5 8 u c = a; | 4 5 4 u c = 9; | 4 5 9 u double d; | 4 5 9 - d = 1.2; | 4 5 9 1.2 d = a; | 4 5 9 4.0 a = d; | ?