MC logo

Assignment and Side Effects II (Answer)

  Practice Questions

  1.      int k = 3, j = 1;
         if (k = j++)
               k = 4;

    Of course, j becomes two. But the if contains an assignment, rather than a comparison. It assigns 1 to 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 =, == pitfall 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 == for 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.

  2.      int m = 6;
         m == 7;

    This compiles. After it runs, m is still 6. The == does not assign anything. Fortunately, this an unlikely typo.

  3.      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.

  4.      int i = 1, m = 1, n = 2;
         i = --m || n++;

    The --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 value of m or n. The result of &&, || or ! is always 1 or 0.

<<Assignment and Side Effects I Question Control Constructs>>