MC logo

Assignment and Side Effects I (Answer)

  Practice Questions

int m = 1, n = 2, i = 0, j = 5;

  1. m = n++ + 3

    n is 3, m is 5. This is a post-increment, so n++ yields 2, producing a total of 5 to be assigned to m. This is also the expression value.

  2. m = ++n

    m, n and the expression value are each 3.

  3. m = (n = 5) + 2

    n gets 5, m gets 7. This is also the expression value. The subexpression (n = 5) assigns 5 to n, then produces the value 5. The 2 is added to the 5 to produce the 7 assigned to n.

  4. i-- && (4 * ++m <= 4 || ++n - 2)

    The i is post-decremented, leaving it at -1, but returning a value of 0. This means that the value of the && must be false, hence the rest of the expression is not evaluated. m remains 1, and n 2. The expression value is 0.

  5. --i || (4 * ++m <= 4 && n++ - 2)

    Here the pre-decrement of i returns the -1 value, which is considered true. The expression value is now determined, so the rest of the expression is not evaluated. m remains 1, and n 2. The expression value is 1.

  6. --i && (4 * ++m <= 4 && n++ - 2)

    Okay, now we get to do something. Here's what happens:

    • The post-decrement --i still returns -1, which is considered true, so (4 * ++m <= 4 && n++ - 2) must be evaluated.
      • We evaluate 4 * ++m <= 4.
      • Since ++m returns 2, this clause is false.
      • This false is the first operand of (4 * ++m <= 4 && n++ - 2), making it evaluate to false, without evaluating n++ - 2.
    • (4 * ++m <= 4 && n++ - 2) is false, so the whole thing is false.
    When the dust settles, i is -1, m is 2, and n remains 2. The expression value is 0.

  7. j > n > m

    This beast evaluates to 0. In sane languages like Pascal or Java, stuff like this is a compile time error. In C, the following:

    • The expression is grouped, by default, left to right, so it is equivalent to (j > n) > m.
    • Well, j is greater than n, so the first part is true.
    • In C, true is 1, so we have 1 > m.
    • Since m is 1, that is 1 > 1, which is false. The expression evaluates to 0.

    The C convention of using the integer type for boolean is why this compiles. In Java or Pascal, at the third step we would have true > 1, which produces a compile time error message to the effect that the types are incompatible. Obviously, since asking if some boolean value is greater than some integer value is nonsense. The integer-for-boolean convention is considered a design error today, and newer languages (like Java) avoid this route. This is not to criticize the designers of C; it is simply that the intervening 25 years of experience with programming languages has something to teach.


<<Legal Identifiers Question Assignment and Side Effects II>>