Note that there are some explanatory texts on larger screens.

plurals
  1. POOpinions on type-punning in C++?
    text
    copied!<p>I'm curious about conventions for type-punning pointers/arrays in C++. Here's the use case I have at the moment:</p> <blockquote> Compute a simple 32-bit checksum over a binary blob of data by treating it as an array of 32-bit integers (we know its total length is a multiple of 4), and then summing up all values and ignoring overflow. </blockquote> <p>I would expect such an function to look like this:</p> <pre><code>uint32_t compute_checksum(const char *data, size_t size) { const uint32_t *udata = /* ??? */; uint32_t checksum = 0; for (size_t i = 0; i != size / 4; ++i) checksum += udata[i]; return udata; } </code></pre> <p>Now the question I have is, what do you consider the "best" way to convert <code>data</code> to <code>udata</code>?</p> <p>C-style cast?</p> <pre><code>udata = (const uint32_t *)data </code></pre> <p>C++ cast that assumes all pointers are convertible?</p> <pre><code>udata = reinterpret_cast&lt;const uint32_t *&gt;(data) </code></pre> <p>C++ cast that between arbitrary pointer types using intermediate <code>void*</code>?</p> <pre><code>udata = static_cast&lt;const uint32_t *&gt;(static_cast&lt;const void *&gt;(data)) </code></pre> <p>Cast through a union?</p> <pre><code>union { const uint32_t *udata; const char *cdata; }; cdata = data; // now use udata </code></pre> <p>I fully realize that this will not be a 100% portable solution, but I am only expecting to use it on a small set of platforms where I know it works (namely unaligned memory accesses and compiler assumptions on pointer aliasing). What would you recommend?</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