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?
Correct answer
D. Left shift of a negative is undefined; right shift is implementation-defined
17 views
D. Left shift of a negative is undefined; right shift is implementation-defined
17 views
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.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.