3 ms·
> C [optionally] supports converting pointers to intptr_t (or uintptr_t) Yes it's optional, but it's "generally" supported. > (even with nominally sufficient
by Dylan16807 4y ago
> C [optionally] supports converting pointers to intptr_t (or uintptr_t)
Yes it's optional, but it's "generally" supported.
> (even with nominally sufficient width)
C99 says: "Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type."
I'm not entirely sure how I'm supposed to parse that, but it sounds like if the result is in range of an integer then it's supposed to work?
I guess you could technically say all results have a zillion added to the actual value? Rules lawyering gets annoying pretty fast.
> and certainly not to a floating point type, which is how NaN boxing works
NaN boxing works by converting to an integer type first. What it does with the bits afterwards is not important to C, as long as it reconstructs the same integer before converting back.
- lokedhs 4y agoThe part you quoted seems pretty clear. It's implementation defined. That's why it works done on most modern architectures, but you can't rely on it in portable code, as there are certainly architectures where it doesn't.
- kazinator 4y agoimplementation-defined is not "optional". The implementation must provide the conversion and document how it's done; it cannot say that, "oh, it's not supported and the program will refuse to compile, or behave erratically". However some stupid definition of behavior could be given, like converting any pointer to integer results in a reliable 0. C has pointer arithmetic; it must support subtraction of pointers that point into the same array-like object. So even on that implementation, you might perhaps be able to obtain a large-ish array and treat that as a heap in which you can convert pointers to integers by subtracting the base.