Bolonha
Bolonha

Reputation: 21

Pre-increment and Post-increment in C

(D) Assume that x, y, and z are all integer variables. After execution, what results will be printed for x, y, and z?

int x=6, y=4, z=2;
printf("%d ", ++x || ++y && ++z);
printf("%d %d %d", z, y, x);

(A )0 6 4 2
(B) 1 7 4 2
(C) 1 2 4 6
(D) 1 2 4 7

Why is the answer D, and why do the Pre-increment Operator of y and z fail?

Upvotes: 1

Views: 117

Answers (1)

4386427
4386427

Reputation: 44339

A number of things are involved:

  1. Operator precedence
  2. Sequence point
  3. The definition of operator ||

Since && has higher operator precedence than ||, the expression ++x || ++y && ++z is the same as ++x || (++y && ++z).

In other words, it's opr1 || opr2 where opr1 is ++x and opr2 is ++y && ++z.

For many C operators taking two operands it's undefined whether opr1 or opr2 is evaluated first (i.e. it can be in any order) but for logical OR it's not the case. For logical OR there is a sequence point between the evaluations of the first and second operands. This means opr1 will be evaluated first.

Further, the definition of logical OR says, opr2 is evaluated if and only if opr1 is zero.

Quote from draft standard N1570:

Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

So for the code in the question, ++x will be evaluated first. As the result is 7 (i.e. non-zero), ++y && ++z will not be evaluated. Consequently, x is incremented and y and z are unchanged.

As logical AND has similar definition with respect to evaluation of operands, it can be seen as

printf("%d ", ++x || ++y && ++z);

is equivalent to

int result;    
if (++x != 0)
{
    result = 1;
}
else if (++y == 0)
{
    result = 0;
}
else if (++z == 0)
{
    result = 0;
}
else
{
    result = 1;
}
printf("%d ", result);

Or in words:

  1. ++x is evaluated
  2. ++y is evaluated if and only if the result of ++x was zero
  3. ++z is evaluated if and only if the result of ++x was zero and the result of ++y was non-zero

Upvotes: 3

Related Questions