1

Specifically I am doing this

Word32 x = 18653184;
Word32 y;
Word16 shift = 269;
y = x >> shift;

I'd expect the result of this logical shift to be 0, but I am instead getting 2277. How does C define this type of operation?

2 Answers 2

5

Yes, it is undefined behavior, according to section 6.5.7 paragraph 3

... If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. After further investigation I have found my c compiler takes mod32 of the amount to shift by and then shifts.
If your computer is an x86 machine, it's actually part of the hardware, more or less. sal/sar/shl/shr require either an immediate value or the %cl register (which is only one byte), and it only uses the low 5 bits of the value when shifting.
@BrandonYates Your processor is likely to be to blame for this behavior. However, it is a good habit not to build any specific expectations of what undefined behavior may do.
I'm actually running on an arm cortex-a8 but I suspect what you said still applies. Thanks for the clarification all.
@BrandonYates: Ah, well in that case ARM has some nice documentation on what happens, if you're curious.
3
ISO c99 : 6.5.7 Bitwise shift operators

3
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

5
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined

You can see c-standard clarifies everything.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.