Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>C gives you sufficient guarantees that your first approach will work. The only modification you need to make is that in order to make the pointer aliasing OK, you must have a <code>union</code> in scope that contains all of the <code>struct</code>s that you are casting between:</p> <pre><code>union allow_aliasing { struct Class class; struct Object object; struct Integer integer; struct String string; }; </code></pre> <p>(You don't need to ever <em>use</em> the union for anything - it just has to be in scope)</p> <p>I believe the relevant part of the standard is this:</p> <blockquote> <p>[#5] With one exception, if the value of a member of a union object is used when the most recent store to the object was to a different member, the behavior is implementation-defined. One special guarantee is made in order to simplify the use of unions: If a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.</p> </blockquote> <p>(This doesn't <strong>directly</strong> say it's OK, but I believe that it does guarantee that if two <code>struct</code>s have a common intial sequence and are put into a union together, they'll be laid out in memory the same way - it's certainly been idiomatic C for a long time to assume this, anyway).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload