Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

#include <stdio.h>

int main()
{
    int i = 4;
    i = i << 2 | i >> 1;
    printf("%d", i);
    return 0;
}

  • A.18
  • B.16
  • C.2
  • D.32

Answer: C

Correct answer: 18

The key is operator precedence: the shift operators bind more tightly than the bitwise OR, so the expression groups as (i << 2) | (i >> 1), not as some left-to-right reading.

With \( i = 4 \), which is 00000100:

i << 2 moves the bits two places left, giving 00010000 = 16 - a left shift by \( n \) multiplies by \( 2^{n} \), and \( 4 \times 4 = 16 \).
i >> 1 moves them one place right, giving 00000010 = 2, that is \( 4 / 2 \).

ORing the two combines their set bits, and since they occupy different positions nothing overlaps: 00010000 | 00000010 = 00010010 = \( 16 + 2 = \) 18.

Both shifts read the original value of i; the assignment happens only once the whole right-hand side has been evaluated, so the left shift does not feed the right one.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.