An unsigned int offset is larger than its size, undefined or not?

The draft 2011 says:

6.5.7 Bitwise shift operators / 4 Result E1 <E2 - left shifted positions E2; freed bits are filled with zeros. If E1 is of unsigned type, the value of the result is E1 ร— 2 ^ E2, given modulo more than the maximum value represented in the type of result. If E1 has a signed type and a non-negative value, and E1 ร— 2E2 is represented in the result type, then this is the resulting value; otherwise, the behavior is undefined.

and

J.2 Undefined behavior . The expression is shifted by a negative number or by an amount greater than or equal to the width (6.5.7).

How to interpret both? Does J.2 use all shifts (unsigned or not) or the explicitly mentioned UB in section 6.5.7 (only for signed).

I mean, what is unsigned int i=...; i <<= sizeof(i)*CHAR_BIT;UB?

+4
source share
2 answers

The paragraph above the one you quoted says the same thing, regardless of subscription:

6.5.7 Bitwise shift operators / 3 Integer promotions are performed for each of the operands. The result type is the advanced left operand. If the value of the correct operand is negative or greater than or equal to the width of the advanced left operand, the behavior is undefined.

, UB, , .

+1

, UB. , :

#include <stdio.h>

#define IMAX_BITS(m) ((m) /((m)%0x3fffffffL+1) /0x3fffffffL %0x3fffffffL *30 \
                  + (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%31+3))

#define UINT_BITS IMAX_BITS((unsigned)-1)

int main(void)
{
    unsigned int foo = 42;
    printf("%d", foo << UINT_BITS);
    return 0;
}

, :

$ gcc -std=c11 -Wall -Wextra -pedantic -oshift shift.c
shift.c: In function 'main':
shift.c:11:22: warning: left shift count >= width of type [-Wshift-count-overflow]
     printf("%d", foo << UINT_BITS);
                      ^~
$ ./shift
42
0

Source: https://habr.com/ru/post/1682727/


All Articles