Hacker News new | past | comments | ask | show | jobs | submit login

Type punning/aliasing with unions is well defined in gcc. Linus even has a humorous rant about it on the topic:

https://www.yodaiken.com/2018/06/07/torvalds-on-aliasing/

Sure, it's compiler-specific, but I'm already using `__attribute__((packed))` anyways.




All undefined behaviour is well defined for each compiler, what it really means is implementation defined and subject to change without notice or documentation with every compiler version or host os what flags are enabled or a thousand other things. Why use an approach which strictly relies on specific versions of specific compilers, rather than a completely portable and standard compliant struct with char array and a few char pointers? Or if you want a convenient interface and aren't explicitly writing for the kernel, switch to a restricted subset of C++ and do it right?


What you're saying is very close to the common fallacious idea about UB, which is that the compiler and computer are machines, and therefore must have some deterministic behaviour when they encounter any given piece of code. But the point and meaning of the term "undefined behaviour" is that it describes the result of operations which are off limits for legal reasons. There is nothing good to be gained from trying to claim that GCC extensions are actually a kind of undefined behaviour. If you know what is meant by UB in the C standard, you won't muddy the waters like this.

"Somebody once told me that in basketball you can't hold the ball and run. I got a basketball and tried it and it worked just fine. He obviously didn't understand basketball." https://blog.regehr.org/archives/213


GCC explicitly states znd documents that type punning through unions will work as expected. This doesn't work by accident. It works very explicitly by design of GCC.

Different GCC versions aren't randomly going to change documented behavior. And when they accidentally do, they will consider it a bug.


Regardless, type punning though a union is not undefined behavior in C the first place [1] [2]. On the other hand, it is undefined in C++, but GCC allows it there too.

[1] https://stackoverflow.com/questions/11639947/is-type-punning...

[2] https://stackoverflow.com/questions/25664848/unions-and-type...


> All undefined behaviour is well defined for each compiler

This is not true.

> what it really means is implementation defined

Implementation-defined behavior is a thing in the standard and is separate from undefined behavior.


What is referred to as implementation defined behaviour is a different class, yes, obviously. I guess nasal deamons was too complicated a piece of irony for you.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: