title: Portable tagged pointers
body: <p>Is there a portable way to implement a tagged pointer in C/C++, like some documented macros that work across platforms and compilers? Or when you tag your pointers you are at your own peril? If such helper functions/macros exist, are they part of any standard or just are available as open source libraries?</p>
  
  <p>Just for those who do not know what tagged pointer is but are interested, it is a way to store some extra data inside a normal pointer, because on most architectures some bits in pointers are always 0 or 1, so you keep your flags/types/hints in those extra bits, and just erase them right before you want to use pointer to dereference some actual value.</p>
  
  <pre><code>const int gc_flag = 1;
  const int flag_mask = 7; // aka 0b00000000000111, because on some theoretical CPU under some arbitrary OS compiled with some random compiler and using some particular malloc last three bits are always zero in pointers.
  
  struct value {
     void *data;
  };
  
  struct value val;
  val.data = &amp;data | gc_flag;
  int data = *(int*)(val.data &amp; flag_mask);
  </code></pre>
  
  <p><a href="https://en.wikipedia.org/wiki/Pointer_tagging" rel="noreferrer">https://en.wikipedia.org/wiki/Pointer_tagging</a></p>