Search code examples
chexoverflowbitwise-operators

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?


Solution

  • 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.