views:

137

answers:

2

I'd like to know at compile-time the range of values for a pointer type. limits.h only specifies maximums and minimums for pure number types. I don't wish to use hard-coded constants, and I prefer not to compute a max using sizeof(foo*).

+3  A: 

I believe I would use intptr_t. It is defined to be the integer that can hold a pointer value, so the min/max values of intptr_t should work.

It might be larger than the values of an actual pointer. But from your explanation of a class that just needs min/max values, I don't believe that you need complete accuracy.

Zan Lynx
Note that `intptr_t` is not currently part of C++; it was added to C in C99 and will be present in the forthcoming C++0x standard.
James McNellis
+3  A: 

Pointers are not numbers. In particular, they're not absolutely ordered - given two random pointers p and q, you cannot subtract one from another and get a meaningful result - it is U.B., unless they both point to the same object (malloc memory block, static or automatic object, etc). So the concept of a permitted range of pointers is meaningless in Standard C++.

Pavel Minaev
That's informative, but I'm not sure it's germane. The only pointer arithmetic being done is comparison, and according to [this answer](http://stackoverflow.com/questions/1418068/what-are-the-operations-supported-by-raw-pointer-and-function-pointer-in-c-c/1418152#1418152), pointers to separate objects are safely and consistently comparable with `std::less<>`. Presumably if there's an absolute ordering there's also an absolute range.
sjbach
Applying operators `<` and `>` in this case would be similarly undefined. But that's a good point regarding `std::less`, actually - though it does not have to be defined in terms of `<` for pointers (the Standard is fairly clear on that) - it still defines an absolute ordering, and, therefore, a range. It doesn't have to map to actual addresses, though, and I'm pretty sure that there's no way to find out the minimum and maximum (in terms of `std::less`) values without enumerating them all.
Pavel Minaev