Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The following is <em>reasonably</em> portable, in the sense that it will work on a lot of different implementations, but not all:</p> <pre><code>union foo { struct {int a, b, c; } data; double padding1; long long padding2; }; static char assert_foo_size[sizeof(foo) % 8 == 0 ? 1 : -1]; </code></pre> <p>That will fail to compile unless either:</p> <ul> <li>the compiler has added some padding to <code>foo</code> to bring it to a multiple of 8, which normally would only happen for reason of an alignment requirement, or</li> <li>the layout of <code>foo.data</code> is extremely strange, or</li> <li>one of <code>long long</code> and <code>double</code> is bigger than 3 ints, and a multiple of 8. Which doesn't necessarily mean it's 8-aligned.</li> </ul> <p>Given that you only need to support 2 compilers though, and clang is fairly gcc-compatible by design, just use the <code>__attribute__</code> that works. Only think of doing anything else if you want to write code now that will (hopefully) work on compilers you're not testing on.</p> <p>C++11 adds <code>alignof</code>, which you can test instead of testing the size. It will remove the false positives, but still leave you with some conforming implementations on which the union fails to create the alignment you want, and hence fails to compile. Also, my <code>sizeof</code> trick is quite limited, it doesn't help at all if your structure has 4 ints instead of only 3, whereas the same thing with <code>alignof</code> does. I don't know what versions of gcc and clang support <code>alignof</code>, which is why I didn't use it to start with. I wouldn't have thought it's difficult to do.</p> <p>By the way, if instances of <code>foo</code> are dynamically allocated then things get easier. Firstly, I suspect that glibc or similar <code>malloc</code> implementations will 8-align anyway -- if there's a basic type with an 8-byte alignment then <code>malloc</code> has to, and I think glibc <code>malloc</code> just does always, rather than worrying about whether there is or not on any given platform. Secondly, there's <code>posix_memalign</code> to be sure. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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