Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1 << 31 cannot be represented by type 'int'?

Why does -fsanitize=undefined throw

runtime error: left shift of 1 by 31 places cannot be represented in type 'int'

on this code

uint32_t z;
z = 1 << 31;

?

like image 358
Geremia Avatar asked Dec 07 '22 13:12

Geremia


2 Answers

Make the 1 unsigned:

uint32_t z;
z = UINT32_C(1) << 31;
like image 176
Geremia Avatar answered Dec 11 '22 10:12

Geremia


Because a left shift of 1 by 31 places cannot be represented in type int.

Mathematically, 1 << 31 is 231, or 2147483648. INT_MAX on a typical system (where int is 32 bits) is one less than that, or 2147483647. If an arithmetic operation on a signed type overflows (yields a result outside the result of the type), the behavior is undefined. (Don't assume it will wrap around. It might, but the language doesn't guarantee it.)

If you need a type that can represent that value, you can use an unsigned type that's at least 32 bits wide, or a signed type that's more than 32 bits wide. unsigned long or long long is guaranteed to be that wide. (The language doesn't guarantee that int is more than 16 bits wide, but it's likely to be 32 on most systems.)

like image 45
Keith Thompson Avatar answered Dec 11 '22 11:12

Keith Thompson