Hacker News new | ask | show | jobs
by MrBingley 2891 days ago
The problem with the first example is that `int` and `unsigned` are not the correct types to be using for array indexing. As we saw, they were 32 bits wide on a 64 bit platform, which lead to an additional sign extension and (in the case of `unsigned`) truncation instruction. However, this can be avoided by using `ptrdiff_t` and `size_t`, which are defined to match the platform size and avoid the extension and truncation altogether. The fact that signed integer overflow being undefined allowed the compiler to elide the `int` truncation is somewhat irrelevant, since using the correct integer types leads to even faster code that doesn't rely on undefined behaviour at all.