This code is an example of a programmer bypassing the type system. The compiler can only syntax check that: 1. A can be initialised with 5. 2. A and B have member's called i, but it doesn't check that they're at the same offset within the struct/class. |
i
is at the same offset this code may not work(and does not work in my example as it output 5 with -O2 with i
at the same offset).A
and B
are not alias types as defined by the strict-aliasing rule so the compiler is allowed to assume that *b
and a
can't be at the same memory location.a
is never modified.a
is never modified the compiler can replace a.i
of line 4 by 5
"safely". In fact a is really modified at line 3 but line 4 doesn't use it, that why it will print 5.
|
|
although I've heard some horror stories about gcc's strict aliasing policy |
If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined52 — the dynamic type of the object, — a cv-qualified version of the dynamic type of the object, — a type similar (as defined in 4.4) to the dynamic type of the object, — a type that is the signed or unsigned type corresponding to the dynamic type of the object, — a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object, — an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union), — a type that is a (possibly cv-qualified) base class type of the dynamic type of the object, — a char or unsigned char type. |
"horror stories"? This is no horror stories, |
I would wager if Linus Torvalds didn't have a horror story to relate |
I can do everithing I want and the compiler shut up |
Which version of mingw are you using? I use the 4.4 and I set only -Wall for warning, I didn't have to add more warnings... |
Do you know the positions of Linus Torvalds about C++? Being myself a C++ programmer, I can't really agree with the point of view of someone who says C++ is an horrible language. |
So I agree this may be an horror story for a C programmer as it's doesn't really fit with the C philosophy I can do everithing I want and the compiler shut up but for a C++ point of view this part of the standard and the optimisatizations it allows is perfectly natural. |