LearnFrenzy
Sign in Take a free test

Bitwise Operators · Predict the Output · Question 11

Right-shifting a negative number with GCC/Clang Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What does this program print with GCC or Clang on x86-64 / ARM64?

main.c
#include <stdio.h>

int main(void) {
    int x = -16;
    printf("%d %d\n", x >> 2, x / 4);
    return 0;
}
  • A 4 -4
  • B 1073741820 -4
  • C -4 4
  • D -4 -4 Correct
Correct Answer: Option D

The result of right-shifting a negative value is implementation-defined; GCC and Clang do an arithmetic shift, copying the sign bit, so −16 >> 2 = −4. (For −15 the two would differ: >> rounds down to −4, division rounds towards zero to −3.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links