Mikefulton wrote:First, it's simply not true that compilers don't have the option of enforcing the spec. I would agree that not checking is probably the default behavior in most cases, but it's also true that some compilers have options to enable runtime checking of certain things that otherwise don't get checked, sort of like having compiler-generated ASSERT statements.
Second, because it says "the result is undefined" that means the compiler is free to do whatever it wants regarding optimization anyway. Therefore, the only way in which optimization could possibly be affected would be if there was runtime enforcement.
Honestly, I don't get your point. Maybe its because I'm kind of "gcc-biased" (since this is the compiler I use most) but there is nothing to enforce any standard.
OK, I'll try this again...
First, to be clear, I never said unions weren't a potential source of huge weird problems.
Second, I didn't mean to suggest that either GCC or other compilers besides GCC commonly implemented any sort of runtime enforcement for union member access rules.
Third, you suggested that the bit about unions was in the spec to "allow compilers for more aggressive code optimizations
". I disagree, because I can't see any way in which the code generation for accessing a union member could be impacted one way or the other by this, if there's no runtime enforcement. Accessing a union member is basically the same thing as accessing a structure member and it's going to end up being one or two instructions of machine code at the end of the compilation. Not really much room for more optimization there.
Fourth, I tried to make the point that if there was
runtime enforcement, even as a special compiler option, the extra code involved would mean that optimization was a bigger concern in many respects. The point here being that this is the only condition in which the idea that the bit in the language spec was motivated by optimization concerns would make any sense.
Fifth, many compilers have options to enable additional runtime checking of various conditions, as a means of testing your code and trying to shake out weird runtime problems that otherwise might be hard to figure out. I don't actually know of any specific compiler that could check this particular thing about union member access, but there are a lot of compilers out there and most of them aren't GCC.
Sixth, just as an observation, it doesn't sound like you're GCC-biased so much as maybe just not experienced with many other compilers? There's actually a fair number of them out there, with different strengths and weaknesses. (The fact that they're not free being the biggest weakness for many GCC fans.)