Is >> ((sizeof) * CHAR_BIT) Defined, UB or IDB?

1. Consider the following:

unsigned int a, b; b = a >> ((sizeof a) * CHAR_BIT); /* or 2nd operand greater than ((sizeof a) * CHAR_BIT) */ 

Is it defined, undefined behavior, or implementation-dependent behavior?

2. Also another question:

In the case of a there is a signed int , and it shifts less than its bit length, is it an implementation of a signed bit shift or an undefined behavior. In both cases:

  • When shifted to the right: a >> 5
  • When moving left: a << 5

EDIT question edited

+4
source share
1 answer

1.

From the C99 standard, section 6.5.7:

Integer promotions are executed for each of the operands. The result type is the advanced left operand. If the value of the right operand is negative or greater than or equal to the width of the advanced left operand, the behavior is undefined.

So this is undefined.

2.

In the same section:

The result of E1 << E2 is E1 left shift of E2 bit positions; freed bits are filled with zeros. If E1 has an unsigned type, the result value is E1 x 2 E2 reduced by one greater than the maximum value represented in the result type. If E1 has a signed type and a non-negative value, and E1 x 2 E2 is represented in the result type, then this is the resulting value; otherwise, the behavior is undefined.

The result of E1 >> E2 is the E1 offset to the right edge of E2 . If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the result value is an integral part of the E1 / 2 E2 relationship . If E1 has a signed type and a negative value, the resulting value is determined by the implementation .

So, for a left shift, it is correctly defined if a signed and positive. It is undefined if a signed and negative.

For a right shift, it is correctly defined if a signed and positive. It is determined by the implementation if a signed and negative.

+7
source

All Articles