1. Home
  2. Computer Science MCQs
  3. C Programming
  4. A program shifts a negative int value both left (x > 1)…

Added 30 Nov -0001

A program shifts a negative int value both left (x << 1) and right (x >> 1). Under the C standard, how are the two operations classified?

  1. Both shifts on negative values are undefined behaviour in standard C
  2. Both shifts are well defined and act on the two's complement bit pattern
  3. Left shift of a negative is implementation-defined, but right shift is undefined
  4. Left shift of a negative is undefined; right shift is implementation-defined Correct answer

Correct answer

D. Left shift of a negative is undefined; right shift is implementation-defined

17 views

MCQSEXAM

Explanation

Shifting a negative signed value left is undefined behaviour because the result may not be representable, while right-shifting a negative value is implementation-defined: arithmetic shift is typical but not mandated. Portable code therefore does bit manipulation on unsigned types, for which both directions are fully defined modulo 2 to the width. The trap is assuming that the compiler's arithmetic right shift is promised by the standard.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is D? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs