What type for operations on pointers
I've searched quite a bit, but couldn't find anything helpful - but then I'm not sure I'm searching for the right thing.
Is there any scalar defined by the standard that has to be at least as large as a pointer? I.e. sizeof(?) >= sizeof(void*).
I need it because I'm writing a small garbage collector and want something along the lines of this:
struct Tag {
uint32_t desc:sizeof(uint32_t)*8-2; // pointer to typedescriptor
uint32_t free:1;
uint32_t mark:1;
};
I'd prefer something that's valid according to the standard (if we're at it, I was quite surprised that sizeof(uint32_t)*8-2 is valid for开发者_开发百科 the bitfield definition - but VS2010 allows it).
So does size_t fulfill this requirement?
Edit: So after my inclusion of both C and C++ lead to some problems (well and there I thought they would be similar in that regard), I'd actually settle for one of them (I don't really need C++ for this part of the code and I can link C and c++ together so that should work). And C99 seems to be the right standard in this case from the answers.
You could include <stdint.h>
(or <cstdint>
) and use uintptr_t
or intptr_t
.
Since MSVC refuses to support C99, you may need to include <Windows.h>
and use ULONG_PTR or LONG_PTR instead. (See C99 stdint.h header and MS Visual Studio)
(Also, please use CHAR_BIT instead of 8.)
C99 has the optional uintptr_t
in <stdint.h>
which guarantees that you can convert between a uintptr_t and a pointer value, though it doesn't say anything about any operations on integer.
Generally, on common platforms a void* is the same as any other pointer and converting a pointer to an integer, manipulating that integer and converting it back to a pointer yields well defined resultes, but C does not guarantee this so you'll have to know the compilers/platform you want to target.
Best you probably can do is use the above mentioned uintptr_t if you have a C99 compiler, or compile a program on the target platform which checks whether sizeof(void*) is equal to any of the sizeof unsigned short,int,long,long long and generate a header file where you typedef your own uintptr according to what the program found out.
精彩评论