I read that you can't do bitmasks on pointers, how come you can't do bitwise operations on pointers?
Is there any way to achieve the same effect?
Does the same apply to C++?
I read that you can't do bitmasks on pointers, how come you can't do bitwise operations on pointers?
Is there any way to achieve the same effect?
Does the same apply to C++?
The reason you can't do bitwise pointer operations is because the standard says you can't. I suppose the reason why the standard says so is because bitwise pointer operations would almost universally result in undefined or (at best) implementation-defined behavior. So there would be nothing you could do that is both useful and portable, unlike simpler operations like addition.
But you can get around it with casting:
#include <stdint.h>
void *ptr1;
// Find page start
void *ptr2 = (void *) ((uintptr_t) ptr1 & ~(uintptr_t) 0xfff)
As for C++, just use reinterpret_cast
instead of the C-style casts.
It's disallowed because the semantics aren't really well defined. You can certainly do it, though. Just cast to uintptr_t
, do the operations and then cast back into a pointer type. That will work in C++, too.
You can't use bitwise operators on pointers because the standards impose very few requirements on how a pointer is represented and what range of values any particular pointer may address. So there's no definition of what it would mean to use those operators on a pointer.
Nevertheless, most compilers on most machines use the obvious mapping of the memory address as the value of the pointer. And most of those will let you cast a pointer to an integral type. You can then do bitwise operations on the value, and even cast it back to a pointer. But that won't be strictly portable or well-defined in general.