Home > Backend Development > C++ > Why is Left Shifting a Negative Number Undefined Behavior in C but Defined in C ?

Why is Left Shifting a Negative Number Undefined Behavior in C but Defined in C ?

Mary-Kate Olsen
Release: 2024-12-11 10:14:11
Original
489 people have browsed it

Why is Left Shifting a Negative Number Undefined Behavior in C but Defined in C  ?

Left Shift Operation and Undefined Behaviour in Negative Operand Context

In C, left shift operations invoke undefined behaviour when the left side operand is negative. According to ISO C99, the behaviour is well-defined only for non-negative signed operands. This is attributed to the potential ambiguity in representing the vacated bits.

C Differences

In contrast to C, C defines the behaviour for left shift operations with negative operands. C -03 specifies that the result is the bit pattern of the left operand shifted left by the specified number of positions, with the vacated bits zero-filled. Furthermore, if the left operand is unsigned, the result is the operand multiplied by 2 raised to the power of the shift count, reduced modulo a certain constant depending on the type.

Reasons for the Undefined Behaviour in C

The undefined behaviour in C arises from the issue of how to handle the vacated bits. In the case of left shift operations, the vacated bits could be filled with either ones or zeros, but the behaviour should be consistent. For example, in the expression -1 << 2, if the vacated bits were filled with ones, the result would be -4, but if they were filled with zeros, the result would be 4026531840.

Right Shift Operation Complexity

On the other hand, right shift operations with negative operands are only implementation-defined, not undefined. This is because the vacated bits are filled with the bit that is being shifted out. With two's complement representation, the sign bit is shifted out, and it simply determines whether the result is positive or negative. The implementation has the flexibility to decide whether to fill the vacated bits with zeros or with the sign bit, making the behaviour implementation-defined.

The above is the detailed content of Why is Left Shifting a Negative Number Undefined Behavior in C but Defined in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template