@hyc@mastodon.social memcpy() is no longer a library function today, it also works like a special code annotation. I believe calling a dummy memcpy() is one legal way to do type punning. If you do it yourself by casting pointers, the result is undefined. If memcpy() does it, it's implementation-defined - which usually gets optimized into a noop by the compiler anyway, if direct access to the underlying memory is acceptable for a particular machine (not always, e.g. alignment-to-machine-word rules).
The root of the problem is that C cannot decide whether it's a high-level or low-level language and sits on the borderline between both. Historically, programmers did all kinds of hacks inside C, like arbitrarily casting memory from and to char * (K&R didn't even have void), or the famous "you're not expected to understand this", which relied on compiler-specific register allocation. But when it became a general-purpose language, for portability and optimizations, only a subset of all possible C code is allowed, which is the part that only operates on "entities" rather than bytes without making assumption about the underlying machine or data representation.
But of course machine-specific assumptions must be made somewhere down the chain. How should the intention of the programmers in these kinds of code be expressed or communicated to the compiler is never systematically considered when C was originally designed.
Embed Notice
HTML Code
Corresponding Notice
- Embed this notice
niconiconi (niconiconi@mk.absturztau.be)'s status on Saturday, 30-Mar-2024 15:09:18 JSTniconiconi