3 ms·
If len and array are both of the same type then the compiler must assume they can alias (or one of them is char*). One has to explicitly state with restrict tha
by sharpneli 6y ago
If len and array are both of the same type then the compiler must assume they can alias (or one of them is char*). One has to explicitly state with restrict that they cannot alias.
In case of similar but where it’s float array[N] etc then compiler can assume that they do not alias.
- geofft 6y agoRight, that's a heuristic, and the consequence of that heuristic is that a bunch of things where you intentionally have pointers of different types to the same memory - the sort of low-level data manipulation that C ought to be good for - is UB unless you are careful about it and you find one of the exceptions to this rule.
- sharpneli 6y agoNot a heuristic. Well defined, even if it could be defined better. I'd personally make all types not alias by default and then have a separate keyword 'alias' to specify things that must alias. One of the reasons why Fortran was faster for decades was the default aliasing rules, restrict finally got us out of that trap. If we'd always assume everything alias plenty of code would become way slower. Also C has well defined ways to access memory via different types. Make an union type and access via that. It makes it explicit.
- AlotOfReading 6y agoIs it really fair to call type punning "well defined"? To my knowledge, it was considered implementation defined from C89 all the way through C11.
- sharpneli 6y agoBefore C11 char* was the only way to do type punning, badly. So it was basically forbidden, but still well defined. Since then they specified that unions are the way to go.
- geofft 6y agoIt's deterministic, but it's still a heuristic in the sense that it's a guess at the underlying intent of the code. You can come up with different, perhaps simpler guesses, but they're still guesses. It's quite common in existing real-world C code to rely on the ability to fill in a variable via a pointer of one type and then access it via a pointer of another type, and you expect the language to properly return the data you wrote to that pointer. The C committee determined that, just about always, that happens when one of the pointers is a char pointer (e.g., you call read() or write() on a struct), and they said that char pointers are allowed to alias by default but others can't. That's their guess, which is mostly accurate. There are much nicer answers here if you're not obligated to be compatible with existing C code - but in that case, especially today, I'd go with one of several other languages that can accurately express intention at the source code level instead of making backwards-incompatible changes to C. :)