title: How portable is using the low bit of a pointer as a flag?
body: <p>If there is for example a class that requires a pointer and a <code>bool</code>. For simplicity an <code>int</code> pointer will be used in examples, but the pointer type is irrelevant as long as it points to something whose <code>size()</code> is more than 1 .</p>
  
  <p>Defining the class with <code>{ bool , int *}</code> data members will result in the class having a size that is double the size of the pointer and a lot of wasted space</p>
  
  <p>If the pointer does not point to a <code>char</code> (or other data of <code>size(1)</code>), then presumably the low bit will always be zero.  The class could defined with <code>{int *}</code> or for convenience: <code>union { int *, uintptr_t }</code></p>
  
  <p>The <code>bool</code> is implemented by setting/clearing the low bit of the pointer as per the logical <code>bool</code> value and clearing the bit when you need to use the pointer.</p>
  
  <p>The defined way:</p>
  
  <pre><code>struct myData
  {
   int * ptr;
   bool flag;
  };
  myData x;
  
  // initialize
  x.ptr = new int;
  x.flag = false;
  
  // set flag true
  x.flag = true;
  
  // set flag false
  x.flag = false;
  
  // use ptr
  *(x.ptr)=7;
  
  // change ptr
  x = y;                // y is another int *
  </code></pre>
  
  <p>And the proposed way:</p>
  
  <pre><code>union tiny
  {
   int * ptr;
   uintptr_t flag;
  };
  tiny x;
  
  // initialize
  x.ptr = new int;
  
  // set flag true
  x.flag |= 1;
  
  // set flag false
  x.flag &amp;= ~1;
  
  // use ptr
  tiny clean=x;      // note that clean will likely be optimized out
  clean.flag &amp;= ~1;  // back to original value as assigned to ptr
  *(clean.ptr)=7;
  
  // change ptr
  bool flag=x.flag;
  x.ptr = y;             // y is another int *
  x.flag |= flag;
  </code></pre>
  
  <p>This seems to be undefined behavior, but how portable is this?</p>