4 ms·
But it is part of the C standard: It's explicitly undefined behavior. There are varieties of type punning that are legal C, so I agree it's confusing to presen
by twoodfin 10y ago
But it is part of the C standard: It's explicitly undefined behavior.
There are varieties of type punning that are legal C, so I agree it's confusing to present this UB implementation artifact as "Type Punning ... in C".
Still a neat magic trick, and an interesting explanation of how it works.
- kbenson 10y agoIn that respect, every possible situation that could happen is part of the standard, as it separates everything into defined and undefined. Cosmic rays twiddling bits in memory is part of the standard by UB under that view. While technically correct, it's useless in practice when taken to this extreme.
- scott_s 10y agotwoodfin is correct in saying that it is explicitly undefined behavior: "If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined." See http://stackoverflow.com/questions/188839/function-pointer-cast-to-different-signature http://stackoverflow.com/questions/188839/function-pointer-c... Your response would make sense if twoodfin claimed it was implicitly undefined behavior. But that's not the case. The standard clearly addresses this case.
- kbenson 10y agoWell, if it relied on just that then that would be accurate. It also relies on the specific architecture and registers available and the calling conventions of the target format (which use different numbers of registers for function arguments).
- _kst_ 10y agoExcept that the C standard explicitly makes no distinction between explicit and implicit undefined behavior. If a "shall" or "shall not" requirement that appears outside of a constraint or runtime constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words "undefined behavior" or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe "behavior that is undefined". N1570 section 4 paragraph 2.
- jheriko 10y agoare you sure? i think in your cosmic ray example, you get well defined behaviour producing unexpected results - its a subtle distinction, but that's part of why UB is horrible, its results can be even less reasonable than those of random bit twiddling. e.g. your standard conforming addition function will still always perform addition - now if by definition that function merely looked like an addition but was actually describing UB, the result could be anything at all, including multiplication (unlikely, but possible) and doing nothing at all (very likely).