I have written this C code which I assume provides portable tagged pointers:
typedef struct {
char tag[2];
int data;
} tagged_int;
#define TAG(x,y) (&(x)->tag[(y)])
#define UNTAG(x) (&(x)[-*(x)])
int main(void) {
tagged_int myint = {{0,1}, 33};
tagged_int *myptr = &myint;
char *myint_tag_1 = TAG(myptr,1);
char *myint_tag_0 = TAG(myptr,0);
char tag_1 = *myint_tag_1;
char tag_0 = *myint_tag_0;
tagged_int *myint_1 = UNTAG(myint_tag_1);
tagged_int *myint_0 = UNTAG(myint_tag_0);
}
However, I am curious about whether it really is portable.
While the array manipulation parts are portable, is char *
to struct *
conversion portable, assuming the char *
refers to the first field/element in the struct *
? (This outputs compiler warnings sadly, but I guess you'd get those with "normal" tagged pointers anyway...)