Assignment and Side Effects II (Answer)
int k = 3, j = 1; if (k = j++) k = 4;
j becomes two. But
if contains an assignment,
rather than a comparison.
k producing a value of 1.
This is treated as true, so the
if body is entered, and
k is assigned 4.
This illustrates the
in C. If you type the wrong one, you can often get code which compiles
and runs, but does something quite unexpected.
Java uses the same operator syntax,
= for assign and
comparison. Java as safer, however, because it has a boolean
type separate from integer. This code is a compile time error
in Java because the
if contains an integer expression where a
boolean one is required.
int m = 6; m == 7;
This compiles. After it runs,
m is still 6. The
== does not
assign anything. Fortunately, this an unlikely typo.
int m; for(m = 3; m--; ) printf("Line.\n");
This prints three lines. The test values are 3, 2, 1, and 0. The first three enter the loop, then the last one terminates.
int i = 1, m = 1, n = 2;
i = --m || n++;
--m is evaluated, which yields 0, so the
n++ must be evaluated. It yields 2, so
the result of the
is true. So
i is 1,
m is 0, and
n is 3.
Note that the the value assigned to
i is not the
n. The result of
! is always 1 or 0.
|Assignment and Side Effects I||Question||Control Constructs|