Why is 32-bit pointer sign-extended when cast to u

2020-04-17 07:44发布

问题:

When compiled as a 32-bit process, the following code prints ffffffff82223333 instead of 82223333, so it seems like a pointer is always sign-extended when converted to uint64_t. Why is that?

#include <stdint.h>
#include <stdio.h>

int main()
{
    void *p = (void*) 0x82223333;
    uint64_t x = (uint64_t) p;
    printf("%llx\n", x);
}

I thought an address can never be negative, so it should be treated as unsigned.

My question is also related to this question (because Windows handles are just typedefs for pointers).

Similar question, but still no explanation why the compiler developers choose to do this.