Home > Backend Development > C++ > body text

Is Right Shifting an Unsigned Integer with a Count Exceeding its Type Width Undefined Behavior in C ?

Linda Hamilton
Release: 2024-11-02 12:16:30
Original
510 people have browsed it

Is Right Shifting an Unsigned Integer with a Count Exceeding its Type Width Undefined Behavior in C  ?

Undefined Behavior of Right Shift with Count Exceeding Type Width

In C , the behavior of the right shift operator (>>) is defined in the standard, specifically in section 5.8, Shift operators. The question arises whether a shift count that is greater than or equal to the width of the type of the left operand is undefined behavior.

The C standard states that the value of E1 >> E2 is the integral part of the quotient of E1/2^E2, where E1 is the left operand and E2 is the right operand. This implies that the behavior is only defined if E1 has an unsigned type or a signed type with a non-negative value and E2 is non-negative.

However, the question considers the case where E1 is of type unsigned int and E2 is 34, which exceeds the width of 32 bits for an unsigned int. The standard explicitly states that the behavior in this case is undefined.

Therefore, despite the statement in the C standard regarding the quotient calculation, the behavior of right shifting an unsigned int with a count greater than 32 is undefined. This is why GCC issues a warning when performing such a shift.

The above is the detailed content of Is Right Shifting an Unsigned Integer with a Count Exceeding its Type Width Undefined Behavior 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!