Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow with hexadecimal but not with variable

I was joking around with bitwise operations, and I notice that

int y = 0x7fffffff;
    
printf("%x",-~y);

prints

80000000

but if I do

printf("%x",-~0x7fffffff);

it gives me an error of overflow:

main.c:65:17: error: integer overflow in expression [-Werror=overflow]
     printf("%x",-~0x7fffffff);

Does anyone know why -~y doesn't have the same behavior?

like image 980
dreamcrash Avatar asked Jul 21 '26 19:07

dreamcrash


1 Answers

The -~y does have the same issue, the compiler just doesn't detect it statically and therefore doesn't warn you about it. When using the integer literal directly, the compiler does the calculation at compile time and realizes that there is an overflow.

like image 88
sth Avatar answered Jul 24 '26 11:07

sth