Home > Backend Development > C++ > Is Left Shifting a Negative Number Undefined Behavior in C but Well-Defined in C ?

Is Left Shifting a Negative Number Undefined Behavior in C but Well-Defined in C ?

Barbara Streisand
Release: 2024-12-24 20:13:17
Original
984 people have browsed it

Is Left Shifting a Negative Number Undefined Behavior in C but Well-Defined in C  ?

Undefined Behavior: Left Shift with Negative Left Operand

According to the ISO C99 standard, the bitwise left shift operation (<<) invokes Undefined Behaviour when the left operand has a negative value. This is because the standard mandates that if the left operand has a signed type and a non-negative value, the result is the product of the left operand and 2 to the power of the shift amount, reduced modulo one more than the maximum value representable in the result type. Otherwise, the behavior is undefined.

Well-Defined Behavior in C

In contrast to C, C ensures well-defined behavior for left shift operations with negative left operands. The ISO C -03 standard specifies that the result is the left operand multiplied by 2 raised to the power of the shift amount, reduced modulo the maximum representable value plus one. This well-defined behavior allows for predictable results even when shifting negative values.

Justification for C 's Well-Defined Behavior

The ISO C committee's decision to define behavior for left shifts with negative left operands was likely driven by the desire for predictable outcomes in various scenarios, including bit manipulation and integer arithmetic.

Implementation-Defined Right Shift with Negative Left Operand

The bitwise right shift operation (>>) with a negative left operand is implementation-defined. This means that the behavior is not specified by the standard and is left to the discretion of the compiler implementer. It typically depends on the target platform and the specific compiler implementation.

The above is the detailed content of Is Left Shifting a Negative Number Undefined Behavior in C but Well-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