3 ms·
If you need to store a pointer in a integer variable, first stop and look very hard at what you're doing and think about whether you really need this. It's usua
by mikeash 12y ago
If you need to store a pointer in a integer variable, first stop and look very hard at what you're doing and think about whether you really need this. It's usually a really, really, really bad idea.
If you have decided that you do really need it, then use the standard C type for "integer type large enough to hold a pointer". Yes, there is one. Actually two. They're called intptr_t and uintptr_t depending on whether you want signed or unsigned.
Similarly, if you subtract two pointers and need to store the answer (this is less of a cause for reflection, but still not too common) then don't toss it into an int and hope that it works. Use the language-provided type for "difference of two pointers", ptrdiff_t.
If you have a value that needs 32 bits of storage, don't throw it in an int and say, hey, int is probably at least 32 bits. Use the language-provided types int32_t and uint32_t.
Understand what types are provided (Wikipedia has a decent summary at http://en.wikipedia.org/wiki/C_data_types http://en.wikipedia.org/wiki/C_data_types), what they mean, and what the guarantees are. Don't fall into the trap of "it works for me, here, now, so it's fine". If you need a particular guarantee (such as the ability to hold a certain range of numbers), ensure that the type you're using provides it.