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

Discussion

What will be the output of the following C code?

#include <stdio.h>
    int main()
    {
        int x = -2;
        x = x >> 1;
        printf("%d\n", x);
    }

 

  • A.1
  • B.-1
  • C.2 - 1 considering int to be 4 bytes
  • D.Either -1 or 1

Answer: B

Correct answer: -1

\( -2 \) in two's complement is ...11111110. Right-shifting a signed negative value is implementation-defined, and every common compiler performs an arithmetic shift, propagating the sign bit into the vacated position.

That gives ...11111111, which is \( -1 \). The result is also what integer division would give with truncation towards negative infinity, which is why the arithmetic shift is chosen. A logical shift would bring in a zero at the top and give a large positive number instead.

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

Post your comment

Please log in or register to post a comment.